循环访问数据帧时出现"The truth value of a Series is ambiguous"错误



我试图将"数量"添加到列表中,条件是"今日价格"列位于标题为active_positions的数据框中"目标价格"列之上。

我尝试了以下代码:

for index, row in active_positions.iterrows():
    if row['Todays Price'] >= row['Target Price']:
        quantities.append(row['Quantity'])

当我尝试此操作时,出现以下错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

查过其他有这个问题的人,我看到的建议是使用"&"而不是"and",这不适用于这种情况(我不认为(。

我也看到了使用 np.where(condition, effect-A, effect-B( 的建议。 这对我不起作用,因为如果不满足条件,并且当我尝试这样做时,我不想向"数量"列表添加任何内容:

for index, row in active_positions.iterrows():
above_target = row['Todays Price'] >= row['Target Price']
quantities.append(np.where(above_target, row['Quantity'],))
Traceback (most recent call last):
  File "<ipython-input-656-9c9f6030d250>", line 3, in <module>
    quantities.append(np.where(above_target, row['Quantity'],))
ValueError: either both or neither of x and y should be given

我知道我可以通过在 np.where 子句中的"row['Quantity]"表达式后添加一个零来解决这个问题,但是就像我说的,我不想在数量列表中添加零。

请指教,谢谢!

为了提高速度,不应尝试循环访问数据帧。如果只希望条件为 True 时的值为 Quantity,则可以应用掩码,如下所示:

import pandas as pd
import numpy as np
a = {'Todays Price': [1, 2, 1, 5, 6], 'Target Price': [1, 3, 2, 4, 3], 
     'Quantity': [10, 11, 12, 13, 15]}
df = pd.DataFrame(a)
quantities = df[df['Todays Price'] >= df['Target Price']]['Quantity']
quantities_list = quantities.values.tolist() # For pure Python list result
# Or perhaps more clearly for the same result:
mask = df['Todays Price'] >= df['Target Price']
quantities = df[mask]['Quantity']
quantities_list = quantities.values.tolist()

相关内容

最新更新