简体   繁体   中英

Python equivalent of Unique function in Matlab

I have a (654 x 2) matrix of integers where many rows are having values which are just permutations of the same column values. (Eg. a certain row has values [2,5] whereas another row has values [5,2]). I need a Python function which treats both the rows as unique and help me deleting the row which comes later when sorted.

Sort each element in the sublist.

a = [[1,2], [3, 4], [2,1]]

#Sorted each element in sublist, I converted list to tuple to provide it as an input in set
li = [tuple(sorted(x)) for x in a]
print(li)
#[(1, 2), (3, 4), (1, 2)]

Then use set to eliminate duplicates.

#Convert tuple back to list
unique_li = [list(t) for t in set(li)]
print(unique_li)
#[[1, 2], [3, 4]]

You could use numpy to sort your array's rows.

a = np.array([[1,2], [3, 4], [2,1]])
a
array([[1, 2],
       [3, 4],
       [2, 1]])

np.ndarray.sort(a)
a
array([[1, 2],
       [3, 4],
       [1, 2]])

The use aray_equal to compare for equality of rows:

np.array_equal(a[0], a[1])
False
np.array_equal(a[0], a[2])
True

And then remove rows using:

np.delete(a, 2, 0)
array([[1, 2],
       [3, 4]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM