根据NaN进行检查时如何选择特定的列Pandas数据框 [英] How to pick specific columns Pandas dataframe when checking against NaN
本文介绍了根据NaN进行检查时如何选择特定的列Pandas数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Python中有一个熊猫数据框,看起来像
I have a pandas dataframe in Python that looks something like
AccountID_x AccountId AmountCD_x AmountDOC_x AmountDoc_x
1 NaN 4001001copa 52.53 52.53 NaN
2 NaN 4001001copa 52.53 52.53 NaN
3 4001001copa NaN 52.53 52.53 NaN
4 NaN 4001001copa 52.53 52.53 NaN
此数据帧是合并命令的结果,该命令将2个数据帧合并在一起.我现在想做的是创建一个新列,该列将添加AccountID_x或AccountId而不是Nan,因此在上面的示例中,第1、2、4行将具有AccountId的值,而第3行将具有某些新列中AccountID_x中的值.
This dataframe is the result of a merge command to merge 2 dataframes together. What I want to do now is create a new column that will add either AccountID_x or AccountId based on which on is not Nan, so in the above example rows 1, 2, 4 would have the value of AccountId in it and row 3 would have the value from AccountID_x in some new column.
推荐答案
您还可以使用apply
传播fillna
:
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)
这篇关于根据NaN进行检查时如何选择特定的列Pandas数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文