连接到: 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。
有人知道解决方案吗?
最佳答案
此处的一种解决方法是简单地使用 fillna
将所有 na
值替换为类似 'NaN'
的字符串。
只需使用:
df1 = df1.fillna('NaN')
df2 = df2.fillna('NaN')
然后使用您现有的代码。
关于python - Pandas :按包含 nan 的列的多个条件过滤数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59160209/