It seems I still struggle with the “in” operator in numpy. Here’s the situation:
>>> a = np.random.randint(1, 10, (2, 2, 3))
>>> a
array([[[9, 8, 8],
[4, 9, 1]],
[[6, 6, 3],
[9, 3, 5]]])
I would like to get the indexes of those triplets whose second element is in (6, 8). The way I intuitively tried is:
>>> a[:, :, 1] in (6, 8)
ValueError: The truth value of an array with more than one element...
My ultimate goal would be to insert at those positions the the number preceding those multiplied by two. Using the example above, a should become:
array([[[9, 18, 8], #8 @ pos #2 --> replaced by 9 @ pos #1 by 2
[4, 9, 1]],
[[6, 12, 3], #6 @ pos #2 --> replaced by 6 @ pos #1 by 2
[9, 3, 5]]])
Thank you in advance for your advice and time!
yields
If you wish to check for membership in a set which is not a simple range, then I like both mac’s idea of using a Python loop and bellamyj’s idea of using np.in1d. Which is faster depends on the size of
check_tuple:test.py:
When N = 10,
using_inis slightly faster:When N = 100,
using_in1dis much faster: