所以我有两个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

推荐答案

您可以使用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

Python相关问答推荐

如果AST请求默认受csref保护,那么在Django中使用@ system_decorator(csref_protect)的目的是什么?

如何让我的Tkinter应用程序适合整个窗口,无论大小如何?

Python中的负前瞻性regex遇到麻烦

如何使用没有Selenium的Python在百思买着陆页面上处理国家/地区 Select ?

如何计算列表列行之间的公共元素

如何让 turtle 通过点击和拖动来绘制?

我从带有langchain的mongoDB中的vector serch获得一个空数组

为什么我的Python代码在if-else声明中的行之前执行if-else声明中的行?

将jit与numpy linSpace函数一起使用时出错

我如何使法国在 map 中完全透明的代码?

Python,Fitting into a System of Equations

numpy卷积与有效

Streamlit应用程序中的Plotly条形图中未正确显示Y轴刻度

Pandas:将多级列名改为一级

为什么抓取的HTML与浏览器判断的元素不同?

如何从数据库上传数据到html?

UNIQUE约束失败:customuser. username

将scipy. sparse矩阵直接保存为常规txt文件

在电影中向西北方向对齐""

用fft计算指数复和代替求和来模拟衍射?