Reputation: 257
I have a 2-dimensional numpy array of following format:
now how to print the frequency of unique elements in this 2d numpy array, so that it returns count([1. 0.]) = 1 and count([0. 1.]) = 1
? I know how to do this using loops, but is there any better pythonic way to do this.
Upvotes: 1
Views: 1940
Reputation: 50864
You can use collections.Counter
, it will give you a dictionary with the sublists as keys and number of occurrences as values
y = np.array([[1., 0.], [0., 1.], [0., 1.]])
counter = collections.Counter(map(tuple, y))
print(counter[0., 1.]) # 2
Upvotes: 0
Reputation: 18426
You can use numpy.unique()
, for axis=0, and pass return_counts=True
, It will return a tuple with unique values, and the counts for these values.
np.unique(arr, return_counts=True, axis=0)
OUTPUT:
(array([[0, 1],
[1, 0]]), array([1, 1], dtype=int64))
Upvotes: 2