python - `Pandas argmax` 在屏蔽后获取所有 `True` 索引(Python 3)(例如 (pd.Series > 0).argmax()))

标签 python pandas indexing mask argmax

我想要做什么,但 argmax 只给我第一个值为 True 的值:

Se = pd.Series(np.arange(6), index=list("abcdef"))
#a    0
#b    1
#c    2
#d    3
#e    4
#f    5
#dtype: int64

mask = (Se % 2 == 0)
#a     True
#b    False
#c     True
#d    False
#e     True
#f    False
#dtype: bool

mask.argmax()
#'a'

我必须做什么:

Se[mask].index
# Index(['a', 'c', 'e'], dtype='object')

这并不算太不方便,但我必须首先实例化Series,这降低了我的工作效率。如果能够做到这一点那就太好了:

(pd.Series(np.arange(6), index=list("abcdef")) % 2 == 0).argmax()

我的问题是:如何使用 argmax 执行此操作?如果这无法通过 argmax 完成,我可以使用 pandas 中的不同函数来完成此操作吗?

最佳答案

您可以使用compress :

idx = pd.Series(np.arange(6), index=list("abcdef")).compress(lambda x: x % 2 == 0).index

结果输出:

Index(['a', 'c', 'e'], dtype='object')

关于python - `Pandas argmax` 在屏蔽后获取所有 `True` 索引(Python 3)(例如 (pd.Series > 0).argmax())),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40557515/

相关文章:

python - 在 python 中应该多久定义一次自定义异常?

python - 使用 df.at 时覆盖列值

python - 从列表中删除 nan - Python

python 数据帧 : get 'set' from DataFrame elements

python - 在列表列表中查找关联值

Oracle 基于函数的索引和 CASE 语句

python - 实体组、ReferenceProperty 或键作为字符串

python - 使用 Django 的 Bootstrap 4 仪表板

c++ - Python PIL Image.tostring ('raw' ) 和 OpenCV 的 IplImage->imageData

javascript - 当给出起始索引时,以循环方式查找数组的值