如果 pandas 列值为真,则将条件语句应用于其他列。 Series 的真值是模棱两可的错误

if a pandas column value is true, apply conditional statement to other column. The truth value of a Series is ambiguous error

我有一列 returns 真或假取决于条件语句 ['gap pos']

取决于该列是真还是假,我需要另一列来遵循 IF ELIF 语句中的特定条件。 ['gap filled']

代码如下:

mgn.loc[mgn['gap_size'] <= 0, 'gap pos'] = False
mgn.loc[mgn['gap_size'] >= 0, 'gap pos'] = True

if (mgn['gap pos'] == True):
    mgn.loc[mgn['Open2Close'] <= -1* (mgn['gap_size']), 'gap filled?'] = 'Filled'
    mgn.loc[mgn['Open2Close'] > -1* (mgn['gap_size']), 'gap filled?'] = 'Not filled'

elif (mgn['gap pos'] == False):
    mgn.loc[mgn['Open2Close'] >= abs(mgn['gap_size']), 'gap filled?'] = 'Filled'
    mgn.loc[mgn['Open2Close'] < abs(mgn['gap_size']), 'gap filled?'] = 'Not filled'

我不想将 .any() 放在 {if (mgn['gap pos'] == True)} 之后,因为这样我的 elif 语句就不会被执行,因为我的 IF 语句已满足。但如果我不放 .any()、.item()、.all() 等

如果我不放任何东西,我会收到: ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

我需要 IF/ELIF 语句来遍历数据框中的每一行。

if和elif条件可以带if条件进去。你能试试这个吗?

mgn.loc[(mgn['Open2Close'] <= -1* (mgn['gap_size'])) & (mgn['gap pos'] == True), 'gap filled?'] = 'Filled' 
mgn.loc[(mgn['Open2Close'] > -1* (mgn['gap_size'])) & (mgn['gap pos'] == True) , 'gap filled?'] = 'Not filled'

mgn.loc[(mgn['Open2Close'] >= abs(mgn['gap_size'])) & (mgn['gap pos'] == False), 'gap filled?'] = 'Filled'
mgn.loc[(mgn['Open2Close'] < abs(mgn['gap_size'])) & (mgn['gap pos'] == False), 'gap filled?'] = 'Not filled'