I saw this code in some examples online and am trying to understand and modify it:
c = a[b == 1]
- Why does this work? It appears
b == 1
returns true for each element ofb
that satisfies the equality. I don't understand how something likea[True]
ends up evaluating to something like "For all values in a for which the same indexed value inb
is equal to 1, copy them toc
"
a
,b
, and c
are all NumPy arrays of the same length containing some data.
I've searched around quite a bit but don't even know what to call this sort of thing.
- If I want to add a second condition, for example:
c = a[b == 1 and d == 1]
I get
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
I know this happens because that combination of equality operations is ambiguous for reasons explained here, but I am unsure of how to add a.any()
or a.all()
into that expression in just one line.
EDIT:
For question 2, c = a[(b == 1) & (d == 1)]
works. Any input on my first question about how/why this works?