Cannot see behavior of unique() method of numpy

Asked 2 years ago, Updated 2 years ago, 55 views

I am having trouble knowing the behavior of the unique() method of numpy at all.

import numpy as np
list_with_dupes=[1, 5, 6, 2, 5, 6, 8, 3, 3, 3, 7, 9]
# (array([1, 2, 3, 5, 6, 7, 8, 9]) Returns an index with deduplication?
print(np.unique(list_with_dupes, return_index=True))
array_with_dupes=np.array([1, 5, 7, 3, 9, 11, 23], [2, 4, 6, 8, 2, 8, 4]])
print(np.unique(array_with_dupes))

If you print using unique() method from two sets, the answer seems to be this value.

#array([0,3,7,1,2,11,6,12], dtype=int64)
#[ 1  2  3  4  5  6  7  8  9 11 23]

I don't understand the meaning of the answer to array([0,3,7,1,2,11,6,12], dtype=int64]). Could you please let me know?

python numpy

2022-09-30 12:07

1 Answers

In np.unique, return_index=True returns a matrix with unique elements and an index for the matrix given as input.I think you can get the same element as unique_array if you put index into the first matrix as shown below.

import numpy as np
list_with_dupes=[1, 5, 6, 2, 5, 6, 8, 3, 3, 3, 7, 9]

unique_array, index_array=np.unique(list_with_dupes, return_index=True)

print('unique array:',unique_array)
# unique array: [1 2 3 5 6789]
print('index array', index_array')
# index array [0 3 7 1 2 11 6 12]
print([list_with_dupes [idx]) for idx in index_array])
# [1, 2, 3, 5, 6, 7, 8, 9]


2022-09-30 12:07

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.