[英]How to merge and update pandas dataframes
如果之前有人問過這個問題,我很抱歉,但我不確定如何在搜索中表達這個問題。
我有 2 個帶有年份列和值列的數據框。 我想根據匹配年份更新第一個數據框,並根據哪個值更大來更新值列。 假設數據框看起來像這樣
>>> 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
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)
為什么不這樣做:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.