Is there an idiomatic way to mask elements of an array in vanilla Python 3? For example:
a = [True, False, True, False]
b = [2, 3, 5, 7]
b[a]
I was hoping b[a]
would return [2, 5]
, but I get an error:
TypeError: list indices must be integers or slices, not list
In R, this works as I expected (using c()
instead of []
to create the lists). I know NumPy has MaskedArray
that can do this, I'm looking for an idiomatic way to do this in plain vanilla Python. Of course, I could use a loop and iterate through the mask list and the element list, but I'm hoping there's a more efficient way to mask elements using a higher level abstraction.
Series
, the syntax is about what you thought :Series(b)[a]
, I've answer with it below – Fourinhand