4

I would like to perform a slicing on a two dimensional numpy array:

type1_c = type1_c[
    (type1_c[:,10]==2) or
    (type1_c[:,10]==3) or
    (type1_c[:,10]==4) or
    (type1_c[:,10]==5) or
    (type1_c[:,10]==6)
]

The syntax looks right; however I got the following error message: 'The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()'

I really don't understand what's going wrong. Any idea?

0

1 Answer 1

7

or is unambiguous when it's between two scalars, but what's the right vector generalization? if x == array([0, 0]) and y == array([0,1]), should x or y be (1) False, because not all pairwise terms or-ed together are True, (2) True, because at least one pairwise or result is true, (3) array([0, 1]), because that's the pairwise result of an or, (4) array([0, 0]), because [0,0] or [0,1] would return [0,0] because nonempty lists are truthy, and so should arrays be?

You could use | here, and treat it as a bitwise issue:

>>> import numpy as np
>>> vec = np.arange(10)
>>> vec[(vec == 2) | (vec == 7)]
array([2, 7])

Explicitly use numpys vectorized logical or:

>>> np.logical_or(vec==3, vec==5)
array([False, False, False,  True, False,  True, False, False, False, False], dtype=bool)
>>> vec[np.logical_or(vec==3, vec==5)]
array([3, 5])

or use in1d, which is far more efficient here:

>>> np.in1d(vec, [2, 7])
array([False, False,  True, False, False, False, False,  True, False, False], dtype=bool)
>>> vec[np.in1d(vec, [2, 7])]
array([2, 7])
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.