I have a pandas series with boolean entries. I would like to get a list of indices where the values are True
.
For example the input pd.Series([True, False, True, True, False, False, False, True])
should yield the output [0,2,3,7]
.
I can do it with a list comprehension, but is there something cleaner or faster?
Boolean Indexing
>>> s = pd.Series([True, False, True, True, False, False, False, True])
>>> s[s].index
Int64Index([0, 2, 3, 7], dtype='int64')
If need a np.array
object, get the .values
>>> s[s].index.values
array([0, 2, 3, 7])
np.nonzero
>>> np.nonzero(s)
(array([0, 2, 3, 7]),)
np.flatnonzero
>>> np.flatnonzero(s)
array([0, 2, 3, 7])
np.where
>>> np.where(s)[0]
array([0, 2, 3, 7])
np.argwhere
>>> np.argwhere(s).ravel()
array([0, 2, 3, 7])
pd.Series.index
>>> s.index[s]
array([0, 2, 3, 7])
filter
>>> [*filter(s.get, s.index)]
[0, 2, 3, 7]
list comprehension
>>> [i for i in s.index if s[i]]
[0, 2, 3, 7]