3

I am trying to find uniques tuples within a numpy array but am unable to. Based on other SO answer I tried np.unique while setting the value for the axis, but it's not providing me what I'm looking for. Here's an example:

I have the following array

b = np.array([[[255, 0, 0], [255, 0, 0]], [[255, 0, 0], [0, 0, 0]]])

I am looking for a way to tell me that it has two tuples in it: (255, 0, 0) and (0, 0, 0). Here are the results from using np.unique:

np.unique(b, axis=0)

array([[[255,   0,   0],
        [  0,   0,   0]],

       [[255,   0,   0],
        [255,   0,   0]]])


np.unique(b, axis=1)

array([[[255,   0,   0],
        [255,   0,   0]],

       [[  0,   0,   0],
        [255,   0,   0]]])

np.unique(b, axis=2)

array([[[  0, 255],
        [  0, 255]],

       [[  0, 255],
        [  0,   0]]])

How do I get it to return [255, 0, 0], [0, 0, 0]?

2 Answers 2

5

Make b into a Nx3 array first. Then use unique.

>>> np.unique(b.reshape(-1, 3), axis=0)
array([[  0,   0,   0],
       [255,   0,   0]])
Sign up to request clarification or add additional context in comments.

Comments

0

Try using a list comprehension:

print(np.array([i for i in b if len(set(map(tuple, i))) == len(i)]))

Output:

[[[255   0   0]
  [  0   0   0]]]

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.