python - Pandas df 错误 - if else 循环中的 "The truth value of a Series is ambiguous."

标签 python pandas

我有一个 pandas df,其中有一个名为 group 的列,由三个值 1,2 和 3 组成。

我正在尝试执行以下 if else 语句:

if df.group == 1:
   (code here)
elif df.group ==2:
   (code here)
else:
   (code here)

当我尝试运行 if else 循环时,它抛出以下错误: ValueError:系列的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

我是否需要在数据帧上使用 np.where 而不是 if else 循环,或者是否有办法通过 if else 循环实现此目的?

最佳答案

你可以像这样迭代:

for idx, val in enumerate(df.itertuples()):
    if df.loc[idx, 'group'] == 1:
       print('1')
    elif df.loc[idx, 'group'] ==2:
       print('2')
    else:
       print('3')
<小时/>

使用np.where引用here

关于python - Pandas df 错误 - if else 循环中的 "The truth value of a Series is ambiguous.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54809890/

相关文章:

python - 相当Pythonic,但不像pandas风格那么令人信服

javascript - 使用安全 WebSocket 连接的 Django channel - WSS ://

python - 如何在没有隐藏额外内存分配的情况下就地修改 numpy 数组?

Python pandas 计算时间,直到列中的值大于当前期间的值

python - 将 Julian 日期转换为数据框中的正常日期?

python - 用列表填充 Pandas 列的空值

python - 如何使用 webapp2 使尾部斜杠可选?

Python:合成类

python - 如何将信号从子进程发送到父进程?

python Pandas : How can I search for a string in a column?