当同一行中存在 NaN 值时返回特定列值

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

我将数据框与静态数据框(电子表格中的表格)合并,生成的数据框如下所示:

Counterparty    DealType       Commodity   Product     
        Aron      Buy           AAA         NaN  
        Aron      Buy           AAA         NaN  
        Aron      Buy           AAA         NaN  
        Aron      Buy           BBB         prod1  
        Aron      Buy           BBB         prod1  
        Aron      Buy           BBB         prod1  
        Aron      Buy          CCC          NaN  
        Aron      Buy          CCC          NaN  
        Aron      Buy          CCC          NaN 

如果数据框的产品列中没有 NaN 值,则合并成功,我的程序可以继续。

但是,如果产品列中确实存在 NaN 值,我需要使用缺失值更新我的电子表格。

这是我的代码,如果有任何 NaN 值,它会返回 true:

if (df['Product'].isnull().any()):
    print('missing values found')
    # get list of missing values
    sys.exit(0)

但我想返回缺失值的列表,例如

['AAA', 'CCC']

python pandas
1个回答
0
投票

您可以使用布尔索引然后获取唯一值:

df.loc[df['Product'].isna(), 'Commodity'].drop_duplicates()

或者:

df.loc[df['Product'].isna(), 'Commodity'].unique()
© www.soinside.com 2019 - 2024. All rights reserved.