获取 pandas 布尔系列为 True 的索引列表 [英] Getting a list of indices where pandas boolean series is True
本文介绍了获取 pandas 布尔系列为 True 的索引列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有布尔条目的熊猫系列.我想获取值为 True
的索引列表.
例如输入 pd.Series([True, False, True, True, False, False, False, True])
应该产生输出[0,2,3,7]
.
我可以使用列表理解来完成,但有没有更简洁或更快速的方法?
解决方案
使用 布尔索引
<预><代码>>>>s = pd.Series([真、假、真、真、假、假、假、真])>>>s[s].indexInt64Index([0, 2, 3, 7], dtype='int64')如果需要np.array
对象,获取.values
使用np.nonzero
<预><代码>>>>np.nonzero(s)(数组([0, 2, 3, 7]),)使用np.flatnonzero
<预><代码>>>>np.flatnonzero(s)数组([0, 2, 3, 7])使用np.where
<预><代码>>>>np.where(s)[0]数组([0, 2, 3, 7])使用np.argwhere
<预><代码>>>>np.argwhere(s).ravel()数组([0, 2, 3, 7])使用pd.Series.index
<预><代码>>>>s.index[s]数组([0, 2, 3, 7])使用python内置的filter
<预><代码>>>>[*过滤器(s.get,s.index)][0, 2, 3, 7]使用列表推导
<预><代码>>>>[i for i in s.index if s[i]][0, 2, 3, 7]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?
解决方案
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]
这篇关于获取 pandas 布尔系列为 True 的索引列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文