Getting a list of indices where pandas boolean series is True

好久不见. 提交于 2020-07-02 08:08:45

问题


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?


回答1:


Using 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])

Using np.nonzero

>>> np.nonzero(s)
(array([0, 2, 3, 7]),)

Using np.flatnonzero

>>> np.flatnonzero(s)
array([0, 2, 3, 7])

Using np.where

>>> np.where(s)[0]
array([0, 2, 3, 7])

Using np.argwhere

>>> np.argwhere(s).ravel()
array([0, 2, 3, 7])

Using pd.Series.index

>>> s.index[s]
array([0, 2, 3, 7])

Using python's built-in filter

>>> [*filter(s.get, s.index)]
[0, 2, 3, 7]

Using list comprehension

>>> [i for i in s.index if s[I]]
[0, 2, 3, 7]


来源:https://stackoverflow.com/questions/52173161/getting-a-list-of-indices-where-pandas-boolean-series-is-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!