如何更新 pandas 现有的数据框架? [英] how to update existing data frame in pandas?
本文介绍了如何更新 pandas 现有的数据框架?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
鉴于这两个数据框:
>>> df1 = pd.DataFrame({'c1':['a','a','b','b'], 'c2':['x','y','x','y'], 'val':0})
>>> df1
c1 c2 val
0 a x 0
1 a y 0
2 b x 0
3 b y 0
>>> df2 = pd.DataFrame({'c1':['a','a','b'], 'c2':['x','y','y'], 'val':[12,31,14]})
>>> df2
c1 c2 val
0 a x 12
1 a y 31
2 b y 14
是否有一个函数从 df2
中的 val元素
相应的索引 df1
导致:
Is there a function that takes the elements of val
from df2
and puts them in the corresponding indexes of df1
, resulting in:
>>> df1_updated
c1 c2 val
0 a x 12
1 a y 31
2 b x 0
3 b y 14
推荐答案
是的,看看 combine_first 或更新。例如:
>>> df1['val'] = df2['val'].combine_first(df1['val'])
>>> df1
Out[26]:
c1 c2 val
0 a x 12
1 a y 31
2 b x 14
3 b y 0
编辑:根据c1和c2结合忽略当前索引:
to combine according to c1 and c2 ignoring the current index:
>>> df1['val'] = df2.set_index(['c1','c2'])['val'].combine_first(df1.set_index(['c1','c2'])['val']).values
>> df1
Out[25]:
c1 c2 val
0 a x 12
1 a y 31
2 b x 0
3 b y 14
这篇关于如何更新 pandas 现有的数据框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文