How to pick specific columns Pandas dataframe when checking against NaN

前端 未结 3 884
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-25 07:52

I have a pandas dataframe in Python that looks something like

       AccountID_x    AccountId  AmountCD_x  AmountDOC_x  AmountDoc_x  
1              NaN  4001001         


        
相关标签:
3条回答
  • 2021-01-25 08:13

    You can use combine_first to combine the two

    df['new_col'] = df['AccountId'].combine_first(df['AccountID_x'])
    
    df['new_col']
    
    1    4001001copa
    2    4001001copa
    3    4001001copa
    4    4001001copa
    
    0 讨论(0)
  • 2021-01-25 08:18

    Try this:

    df['new_column'] = df.apply(lambda x: x['AccountId'] if pd.isnull(x['AccountID_x']) else x['AccountID_x'], axis=1)
    
    0 讨论(0)
  • 2021-01-25 08:26

    You can also propagate fillna using apply:

    df2['newcolumn'] = df2[['AccountID_x','AccountId']].apply(lambda x: x.fillna(method='ffill')[-1], axis=1)
    

    Or equivalently (in your case):

    df2['newcolumn'] = df2[['AccountID_x','AccountId']].apply(lambda x: x.fillna(method='bfill')[0], axis=1)
    
    0 讨论(0)
提交回复
热议问题