1

I have a 2-dimensional numpy array of following format:

enter image description here

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.

2 Answers 2

2

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))
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.