pandas 获取熊猫布尔系列为 True 的索引列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52173161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting a list of indices where pandas boolean series is True
提问by James McKeown
I have a pandas series with boolean entries. I would like to get a list of indices where the values are True
.
我有一个带有布尔条目的Pandas系列。我想获取值为 的索引列表True
。
For example the input pd.Series([True, False, True, True, False, False, False, True])
例如输入 pd.Series([True, False, True, True, False, False, False, True])
should yield the output [0,2,3,7]
.
应该产生输出[0,2,3,7]
。
I can do it with a list comprehension, but is there something cleaner or faster?
我可以通过列表理解来做到这一点,但是有什么更简洁或更快速的方法吗?
回答by rafaelc
Using Boolean Indexing
使用 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
如果需要一个np.array
对象,获取.values
>>> s[s].index.values
array([0, 2, 3, 7])
Using np.nonzero
使用 np.nonzero
>>> np.nonzero(s)
(array([0, 2, 3, 7]),)
Using np.flatnonzero
使用 np.flatnonzero
>>> np.flatnonzero(s)
array([0, 2, 3, 7])
Using np.where
使用 np.where
>>> np.where(s)[0]
array([0, 2, 3, 7])
Using np.argwhere
使用 np.argwhere
>>> np.argwhere(s).ravel()
array([0, 2, 3, 7])
Using pd.Series.index
使用 pd.Series.index
>>> s.index[s]
array([0, 2, 3, 7])
Using python's built-in filter
使用python的内置 filter
>>> [*filter(s.get, s.index)]
[0, 2, 3, 7]
Using list comprehension
使用 list comprehension
>>> [i for i in s.index if s[I]]
[0, 2, 3, 7]