熊猫:使用包含nan的列的多种条件过滤数据框

时间:2019-12-03 15:18:11

标签: python pandas dataframe

已连接到: Pandas: add column with index of matching row from other dataframe

将多个列与第二个数据帧中的相应列匹配,并从第二个数据帧中返回匹配行的索引。

df1['new_column'] =  df1.apply(lambda x: df2[(df2.col1 == x.col1)
                                           & (df2.col2 == x.col2)
                                           & (df2.col3 == x.col3)
                                           & (df2.col4 == x.col4)
                                           & (df2.col5 == x.col5)].index[0], axis=1)

上面的代码就像一个符咒一样工作……除非其中一列可以包含nan值,否则nan!= nan。 换句话说,即使 df1 中的 col1:col4 与两个 df1中的 df2 col5 匹配, / strong>和 df2 nan ,它不匹配它并返回空索引对象。
无论col1:col5是否匹配,无论它们包含值还是nan,我都需要返回True。

有人知道解决方案吗?

1 个答案:

答案 0 :(得分:2)

这里的一种解决方法是简单地使用fillna用类似na的字符串替换所有'NaN'值。

只需使用:

df1 = df1.fillna('NaN')
df2 = df2.fillna('NaN')

然后使用您现有的代码。