首页 > 解决方案 > 获取真实值的熊猫系列标签,而不将系列存储在临时变量中

问题描述

输入:

pd.Series([True, False, True, False], index=['a', 'b', 'c', 'd'])

期望的结果:

['a', 'c']  # can be in pd.Series or np.array format, doesn't matter.

我想要一个不将系列存储在临时变量中的解决方案,例如

s = pd.Series([True, False, True, False], index=['a', 'b', 'c', 'd'])
s[s == True].index

将系列存储在 s 中,并使用它两次。

我正在寻找的解决方案就像

np.where(s)

但返回真实值的标签,而不是它们的整数索引。

笔记:

这个问题与这个问题类似但更具体。

标签: pythonpandas

解决方案


我总是通过loc

pd.Series([True, False, True, False], index=['a', 'b', 'c', 'd']).loc[lambda x : x].index
Index(['a', 'c'], dtype='object')

推荐阅读