gpt4 book ai didi

python - 在 Panda Dataframe 中附加 bool 列

转载 作者:太空狗 更新时间:2023-10-29 21:19:42 24 4
gpt4 key购买 nike

我正在学习 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().

我理解 Pandas 系列 ( 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

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

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

关于python - 在 Panda Dataframe 中附加 bool 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30912403/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com