【问题标题】:Appending Boolean Column in Panda Dataframe在 Panda Dataframe 中附加布尔列
【发布时间】:2015-09-03 22:01:03
【问题描述】:

我正在学习 pandas,但在这里遇到了这个问题。

我创建了一个数据框来跟踪所有用户以及他们做某事的次数。

为了更好地理解我创建这个示例的问题:

import pandas as pd
data = [
    {'username': 'me',  'bought_apples': 2, 'bought_pears': 0},
    {'username': 'you', 'bought_apples': 1, 'bought_pears': 1}
]
df = pd.DataFrame(data)
df['bought_something'] = df['bought_apples'] > 0 or df['bought_pears'] > 0

在最后一行中,我想添加一列,表明他们的用户是否购买过东西。

弹出这个错误:

ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

我理解熊猫系列 (also explained here) 中的歧义点,但我无法将其与问题联系起来。

有趣的是,这有效

df['bought_something'] = df['bought_apples'] > 0

谁能帮帮我?

【问题讨论】:

    标签: python pandas ipython-notebook


    【解决方案1】:

    您可以逐行调用sum 并比较它是否大于0

    In [105]:
    df['bought_something'] = df[['bought_apples','bought_pears']].sum(axis=1) > 0
    df
    
    Out[105]:
       bought_apples  bought_pears username bought_something
    0              2             0       me             True
    1              1             1      you             True
    

    关于您最初的尝试,错误消息告诉您将标量与数组进行比较是不明确的,如果您想要 or 布尔条件,那么您需要使用按位运算符 | 并包装由于运算符优先级,括号中的条件:

    In [111]:
    df['bought_something'] = ((df['bought_apples'] > 0) | (df['bought_pears'] > 0))
    df
    
    Out[111]:
       bought_apples  bought_pears username bought_something
    0              2             0       me             True
    1              1             1      you             True
    

    【讨论】:

      【解决方案2】:

      该错误的原因是您使用“或”来“连接”两个布尔向量而不是布尔标量。这就是为什么它说它是模棱两可的。

      【讨论】:

        猜你喜欢
        • 2018-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-21
        • 2012-08-14
        • 1970-01-01
        • 2020-01-05
        • 1970-01-01
        相关资源
        最近更新 更多