python - 获取 pandas boolean 系列为 True 的索引列表

标签 python pandas boolean series boolean-indexing

我有一个带有 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/

相关文章:

python - 在 Python 中 : How to remove an object from a list if it is only referenced in that list?

python - Django 压缩器找不到任何 `compress` 标签

python - 在 Pandas 数据框中扩展时间序列数据

javascript - 为什么我的 switch 语句参数需要 boolean 值?

android - 如何从数据库获取 boolean 值并将其添加到 TextView 中?

python - 使用cx_oracle批量下载表

python - 将用户输入实现到神经网络中

python - CSV、Python 中的字符串大小写运算

python数据框创建新列

python - 在 python 中使用 boolean 列表