繁体   English   中英

按索引合并两个 pandas 数据帧并替换 Python 中的列值

[英]Merge two pandas dataframes by index and replace column values in Python

我有两个 pandas 数据帧:

DF1

index = np.arange('2020-01-01 00:00', '2020-01-01 00:04', dtype='datetime64[m]')
df = np.random.randint(100,500, size=(4,4))
columns =['Open','High','Low','Close']
df = pd.DataFrame(df, index=index, columns = columns)
df.index.name = 'Time'

                     Open  High  Low  Close
Time                                       
2020-01-01 00:00:00   266   397  177    475
2020-01-01 00:01:00   362   135  456    235
2020-01-01 00:02:00   315   298  296    493
2020-01-01 00:03:00   324   411  198    101

DF2

index = np.arange('2020-01-01 00:02', '2020-01-01 00:05', dtype='datetime64[m]')
df2 = np.random.randint(100,500, size=(3,4))
columns =['Open','High','Low','Close']
df2 = pd.DataFrame(df2, index=index, columns = columns)
df2.index.name = 'Time'

                     Open  High  Low  Close
Time                                       
2020-01-01 00:02:00   430   394  131    490
2020-01-01 00:03:00   190   211  394    359
2020-01-01 00:04:00   192   291  143    350

我需要按索引(时间)合并两个数据帧,并将 DF1 的列值替换为 DF2 的列值。

这是我预期的 output:

                     Open  High  Low  Close
Time                                       
2020-01-01 00:00:00   266   397  177    475 ->>>> Correspond to DF1
2020-01-01 00:01:00   362   135  456    235 ->>>> Correspond to DF1
2020-01-01 00:02:00   430   394  131    490 ->>>> Correspond to DF2
2020-01-01 00:03:00   190   211  394    359 ->>>> Correspond to DF2
2020-01-01 00:04:00   192   291  143    350 ->>>> Correspond to DF2

我尝试了几个函数,包括合并或 concat (concat([df1, df2], join="inner")) 但没有成功。 任何帮助将不胜感激。 谢谢!

尝试这个:

df2.combine_first(df)
                     Open  High  Low  Close
Time                                       
2020-01-01 00:00:00   266   397  177    475
2020-01-01 00:01:00   362   135  456    235
2020-01-01 00:02:00   430   394  131    490
2020-01-01 00:03:00   190   211  394    359
2020-01-01 00:04:00   192   291  143    350

因为您提到pd.concat ,所以您可以这样做。

out = pd.concat([df, df2])
out = out[~out.index.duplicated(keep='last')]
print(out)
                     Open  High  Low  Close
Time                                       
2020-01-01 00:00:00   266   397  177    475
2020-01-01 00:01:00   362   135  456    235
2020-01-01 00:02:00   430   394  131    490
2020-01-01 00:03:00   190   211  394    359
2020-01-01 00:04:00   192   291  143    350

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM