pandas 离开加入并更新现有专栏 [英] pandas left join and update existing column
本文介绍了 pandas 离开加入并更新现有专栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是熊猫新手,似乎无法通过合并功能使用它:
I am new to pandas and can't seem to get this to work with merge function:
>>> left >>> right
a b c a c d
0 1 4 9 0 1 7 13
1 2 5 10 1 2 8 14
2 3 6 11 2 3 9 15
3 4 7 12
在列a上有一个左联接,我想通过联接键来更新公共列.请注意,c列中的最后一个值来自LEFT表,因为没有匹配项.
With a left join on column a, I would like to update common columns BY THE JOINED KEYS. Note last value in column c is from LEFT table since there is no match.
>>> final
a b c d
0 1 4 7 13
1 2 5 8 14
2 3 6 9 15
3 4 7 12 NAN
如何使用Pandas合并功能执行此操作?谢谢.
How should I do this with Pandas merge function? Thank you.
推荐答案
One way to do this is to set the a column as the index and update
:
In [11]: left_a = left.set_index('a')
In [12]: right_a = right.set_index('a')
注意:update
仅执行左连接(不合并),因此,除了set_index之外,还需要包括left_a
中不存在的其他列.
Note: update
only does a left join (not merges), so as well as set_index you also need to include the additional columns not present in left_a
.
In [13]: res = left_a.reindex(columns=left_a.columns.union(right_a.columns))
In [14]: res.update(right_a)
In [15]: res.reset_index(inplace=True)
In [16]: res
Out[16]:
a b c d
0 1 4 7 13
1 2 5 8 14
2 3 6 9 15
3 4 7 12 NaN
这篇关于 pandas 离开加入并更新现有专栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文