在 Panda Dataframe 中附加布尔列

Appending Boolean Column in Panda Dataframe

我正在学习 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: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

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

有趣的是这有效

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

谁能帮帮我?

您可以按行调用 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

该错误的原因是您使用 'or' 到 'join' 两个布尔向量而不是布尔标量。这就是为什么它说它是模棱两可的。