【问题标题】:Get pandas series labels of true values without storing the series in a temp variable获取真实值的熊猫系列标签,而不将系列存储在临时变量中
【发布时间】:2020-10-18 05:38:10
【问题描述】:

输入:

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)

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

注意事项:

这个问题类似于this one,但更具体。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    我总是传给loc

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

    【讨论】:

    • 啊哈!很好的答案。那么 pandas 中没有内置函数吗?
    • @AlexLenail 我不这么认为~
    猜你喜欢
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-03
    • 2017-06-13
    • 2020-03-30
    • 2021-01-14
    相关资源
    最近更新 更多