我有一个带有 boolean 条目的 Pandas 系列。我想获取值为 True
的索引列表。
例如输入 pd.Series([True, False, True, True, False, False, False, True])
应该产生输出 [0,2,3,7]
。
我可以通过列表推导来做到这一点,但是有什么更干净或更快的东西吗?
最佳答案
使用Boolean Indexing
>>> s = pd.Series([True, False, True, True, False, False, False, True])
>>> s[s].index
Int64Index([0, 2, 3, 7], dtype='int64')
如果需要一个np.array
对象,获取.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])
使用 python 的内置 filter
>>> [*filter(s.get, s.index)]
[0, 2, 3, 7]
使用列表理解
>>> [i for i in s.index if s[i]]
[0, 2, 3, 7]
关于python - 获取 pandas boolean 系列为 True 的索引列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52173161/