[英]Need help converting a merge function from R to Python, shape of resulting df is the same but losing more rows in Python after dropping duplicates
[英]Panda's left merge: resulting table has more rows, prevent duplicates
我有 2 个数据框。 df1 有 39780 行,df2 有 8900454 行
我要合并的 df1 列: ['postalcode','housenumber', 'suffix']
'suffix' 列包含一些 NAN。
df2 列:
['postalcode_right','housenumber_right', 'suffix_right', 'index_right']
(名为“index_right”的列不是该数据框的索引。)
df2 = pd.merge(df1, df2, how='left', left_on=['postalcode','housenumber', 'suffix'], right_on = ['postalcode_right','housenumber_right', 'suffix_right'])
因为 df1.suffix 包含 NAN 右边的一些行匹配左边的多行。
如何防止这种情况或清除多次匹配的行的“index_right”值?
您不应该寻找按空值分组。 一方面,从分析的角度来看,这没有多大意义。
您可以将NA
值转换为填充字符串,例如'NULL'
:
left_cols = ['postalcode', 'housenumber', 'suffix']
right_cols = ['postalcode_right', 'housenumber_right', 'suffix_right']]
df1[left_cols] = df1[left_cols].fillna('NULL')
df2[right_cols] = df2[right_cols].fillna('NULL')
然后在合并之前在right
数据框中删除重复项:
res = pd.merge(df1, df2.drop_duplicates(subset=right_cols),
how='left', left_on=left_cols, right_on=right_cols)
这将确保res
具有与df1
相同的行数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.