4

I am rewriting one code

nd = unique(nd,'rows');

Documentation from The Mathworks

C = unique(A,'rows') treats each row of A as a single entity and returns the unique rows of A. The rows of the array C are in sorted order.

Is there something like this in Python or I have to use sort?

Suever
  • 64,497
  • 14
  • 82
  • 101
Sinisha
  • 107
  • 1
  • 2
  • 7

2 Answers2

3
import numpy as np

# Having an array:
a = [1,2,2,3,4,4,3]
print ("Original vector:")
print(a)

# Printting unique values of a:
print ("Unique values of a:")
print (np.unique(a))

# Other option:
print  ("Another way:")
print (set(a))

Ouput:

Original vector:
[1, 2, 2, 3, 4, 4, 3]
Unique values of a:
[1 2 3 4]
Another way:
{1, 2, 3, 4}
Hugo Reyes
  • 1,555
  • 2
  • 12
  • 21
  • The MATLAB `unique` with 'rows' specified finds the unique *rows*. `np.unique` will return the unique elements from the flattened array. For 2D arrays see https://stackoverflow.com/questions/16970982/find-unique-rows-in-numpy-array – Klimaat Mar 22 '17 at 19:48
0

Python:

a = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4], [2, 3, 4],[2, 3, 5],[1, 0, 0],[2,2,5],[2,3,5]])
c, ia, ic= np.unique(a,return_index=True,return_inverse=True, axis=0)

This will give the same result as the unique function of Matlab. The only difference is the base index which starts from 0 in Python.

Stupid420
  • 1,347
  • 3
  • 19
  • 44