我有一个 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/