pandas 我有一个excel表格,我更新了季度财务数据,我想自动化的过程中更新它每个季度

23c0lvtd  于 2023-03-28  发布在  其他
关注(0)|答案(1)|浏览(107)

所以我有两个df,一个是历史数据的时间序列(df1),另一个是最近一年的数据(df2)

so for example 
df(1):
 Date   DebtGDP   Credit    Expenditure
 2020  0.053078  0.501184    757.000000  
 2021  0.935433  0.050437    229.000000 
 2022      NaN       NaN        NaN
 2023      NaN       NaN        NaN

df(2):
 Date   DebtGDP   Credit    Expenditure
 2022  0.056078  0.401184    757.000000
 2023  0.605842  0.661184    900.000000

I want df1 to read from df2 and update the recent ones

所需输出:

df(1) would be:
 Date   DebtGDP   Credit    Expenditure
 2020  0.053078  0.501184    757.000000  
 2021  0.935433  0.050437    229.000000 
 2022  0.056078  0.401184    757.000000
 2023  0.605842  0.661184    900.000000
lsmepo6l

lsmepo6l1#

可以使用mergecombine_first

out = df1.combine_first(df2.merge(df1[['Date']], how='right'))

或者:

out = df1.set_index('Date').combine_first(df2.set_index('Date')).reset_index()

输出:

Date   DebtGDP    Credit  Expenditure
0  2020  0.053078  0.501184        757.0
1  2021  0.935433  0.050437        229.0
2  2022  0.056078  0.401184        757.0
3  2023  0.605842  0.661184        900.0

相关问题