如果一个pandas列的值为真,则对其他列应用条件语句。一个Series的真值是模糊的错误。

问题描述 投票:0回答:1

我有一个列,根据条件语句['gap pos']返回True或False。

根据该列是真还是假,我需要另一列在IF ELIF语句中遵循特定条件。['填空']

下面是代码。

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()。

我需要我的IFELIF语句来迭代数据框中的每一行。

python pandas valueerror
1个回答
1
投票

你可以把if条件带入if和elif条件里面。你可以试试这个吗?

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'
© www.soinside.com 2019 - 2024. All rights reserved.