【发布时间】:2023-03-16 08:35:02
【问题描述】:
我正在尝试遍历数据框中的两列,并根据上述两个列值将1 或0 添加到新列中。例如,如果 A 列 > B 列,则将 1 添加到 C 列。但是,我不断收到以下错误,我不知道为什么。
ValueError: The truth value of a Series is ambiguous. Use a.empty,
a.bool(), a.item(), a.any() or a.all().
我的代码:
for i in df.itertuples():
if df['AdjClose'] > df['30ma']:
df['position'] = 1
elif df['AdjClose'] < df['30ma']:
df['position'] = 0
【问题讨论】:
-
下面的答案不是很好。你应该使用
df['position'] = (df['AdjClose'] > df['30ma']).astype(int)。
标签: python python-3.x pandas loops