如何合并和更新熊猫数据框

时间:2019-01-11 07:56:36

标签: python pandas

很抱歉,是否曾经有人问过这个问题,但是我不确定如何在搜索中输入这个问题。

我有2个数据框,其中包含年列和值列。我想根据匹配的年份对第一个数据框进行udp处理,并根据较大的值更新value列。假设数据帧看起来像这样

>>> import pandas as pd
>>> x = [1999, 2000, 2001]
>>> y = [0, 0, 0]
>>> df1 = pd.DataFrame({'year': x, 'value': y})
>>> df1

   year   value
0  1999   0
1  2000   0
2  2001   0

>>> x2 = [1999, 2003, 2004]
>>> y2 = [5, 0, 0]
>>> df2 = pd.DataFrame({'year': x2, 'value': y2})
>>> df2

   year   value
0  1999   5
1  2003   0
2  2004   0

我希望更新的数据框(df1)看起来像这样。有没有简单的方法可以做到这一点?

   year   value
0  1999   5
1  2000   0
2  2001   0

2 个答案:

答案 0 :(得分:1)

使用mergemap

df = df1.merge(df2, on=['year'], how='outer')
df['max'] = df.filter(like='value').max(1)
df1['value'] = df1['year'].map(df.set_index('year')['max'])

print(df1)
   year  value
0  1999    5.0
1  2000    0.0
2  2001    0.0

编辑:要了解哪些行已更改,请使用:

#intialize the `value` column to `temp` column
df1['temp'] = df1['value']
#now use the above code to change the `value` column
#check which rows are changed with respect to `temp` column
df1['Changed_Values'] = df1['temp'].ne(df1['value'])
#finally drop temporary column
df1.drop('temp', axis=1, inplace=True)

答案 1 :(得分:0)

为什么不这样做:

if df1.value.sum()<df2.value.sum():
    df1.value = df2.value

或者:

if df1['value'].sum()<df2['value'].sum():
    df1['value'] = df2['value']

现在:

print(df1)

是:

   year  value
0  1999      5
1  2000      0
2  2001      0
相关问题