![](/img/trans.png)
[英]Error in concating different columns from different dfs into one df in pandas
[英]Cross reference columns from two pandas DFs. If a match is found, fill information from one DF to the other
我试图交叉引用一个具有一列地址和邮政编码的DF,与另一个具有地址和一个完全空的列的DF,该列将接受邮政编码。 如果地址在df1和df2之间匹配,则df2应该接受邮政编码形式df1。
DF1
Address PostCode A 1 B 2 C 3 D 4
DF2
Address PostCode ARCZ
我想实现的目标是df2应该是:
DF2
Address PostCode A 1 R NaN C 3 Z Nan
我对此有点迷茫,我尝试使用'isin'和其他命令来加入,合并,布尔值。 我似乎无法弄清楚这一点。 任何意见,将不胜感激。
如果您对dtype = object的PostCode没问题
>>> df1
Address PostCode
0 A 1
1 B 2
2 C 3
3 D 4
>>> df2
Address PostCode
0 A
1 R
2 C
3 Z
>>> df3 = df2.merge(df1, on='Address', how='left')
>>> df3['PostCode'] = df3.PostCode_y.combine_first(df3.PostCode_x)
>>> df3
Address PostCode_x PostCode_y PostCode
0 A 1.0 1
1 R NaN
2 C 3.0 3
3 Z NaN
>>> df3[['Address', 'PostCode']]
Address PostCode
0 A 1
1 R
2 C 3
3 Z
或者,您可以执行此操作,但它将PostCode更改为dtype = float64以便处理NaN。 您以后可以随时修复数据类型。
>>> df2.Address.map(df1.set_index('Address').PostCode)
0 1.0
1 NaN
2 3.0
3 NaN
Name: Address, dtype: float64
请注意,使用df1.set_index('Address')。PostCode是一个索引系列。 如果您有一个地址到邮政编码的字典,则可以得到相同的效果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.