pandas 如何更新熊猫中的现有数据框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18726497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 21:08:57  来源:igfitidea点击:

how to update existing data frame in pandas?

pythonpandasdataframe

提问by HappyPy

Given these two data frames:

鉴于这两个数据框:

>>> 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

Is there a function that takes the elements of valfrom df2and puts them in the corresponding indexes of df1, resulting in:

是否有一个函数可以获取valfrom的元素df2并将它们放在 的相应索引中df1,从而导致:

>>> df1_updated 
  c1 c2  val
0  a  x   12
1  a  y   31
2  b  x    0
3  b  y   14

回答by elyase

Yes, take a look at combine_firstor update. For example:

是的,看看combine_firstupdate。例如:

>>> 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

EDIT: to combine according to c1 and c2 ignoring the current index:

编辑:根据 c1 和 c2 组合忽略当前索引:

>>> 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