1

I would like to check if a numpy tuple is present in a numpy array of tuples.

When I run the following code:

import numpy as np

myarray=np.array([[0,1],[0,2],[0,3],[4,4]])
test1=np.array([0,3])
test2=np.array([4,0])

myarraylst=myarray.tolist()
test1lst=test1.tolist()
test2lst=test2.tolist()

print(test1lst in myarraylst)
print(test2lst in myarraylst)

I get "True" for the first test and "False" for the second test as it should be. Is there a way to do this without converting the numpy arrays to python lists ?

Many Thanks !

2
  • The question refers to "bumpy tuples" mistakenly and not "numpy" tuples as it should be. Sorry ! Commented Mar 11, 2022 at 11:47
  • I thought tuples were sets of two values. Following your remark I have found what tuple means in Python. Thanks for pointing this out ! Commented Mar 11, 2022 at 19:28

1 Answer 1

0

For lists, the in tests for the identity/equality of the sublists. For arrays in, or np.isin the evaluation goes all the down, to the numeric elements.

In [181]: myarray = np.array([[0, 1], [0, 2], [0, 3], [4, 4]])
     ...: test1 = np.array([0, 3])
     ...: test2 = np.array([4, 0])

But we can do an elementwise test:

In [183]: test1 == myarray
Out[183]: 
array([[ True, False],
       [ True, False],
       [ True,  True],
       [False, False]])

Here one array is (4,2) and the other (2,) shape, which broadcast together just fine. For other cases we may need to tweak dimensions.

You just want the rows where both elements match:

In [184]: (test1 == myarray).all(axis=1)
Out[184]: array([False, False,  True, False])
In [185]: (test2 == myarray).all(axis=1)
Out[185]: array([False, False, False, False])

and reduce those arrays to one value with any:

In [187]: (test1 == myarray).all(axis=1).any()
Out[187]: True
In [188]: (test2 == myarray).all(axis=1).any()
Out[188]: False
Sign up to request clarification or add additional context in comments.

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.