以下是一个示例代码,展示如何按最接近的日期合并两个数据框:
import pandas as pd
# 创建示例数据框 df1 和 df2
df1 = pd.DataFrame({'日期': pd.to_datetime(['2020-01-01', '2020-01-03', '2020-01-05']),
'数值1': [1, 2, 3]})
df2 = pd.DataFrame({'日期': pd.to_datetime(['2020-01-02', '2020-01-04', '2020-01-06']),
'数值2': [4, 5, 6]})
# 将日期设置为索引
df1.set_index('日期', inplace=True)
df2.set_index('日期', inplace=True)
# 合并数据框,使用最接近的日期进行合并
merged_df = df1.merge(df2, how='outer', left_index=True, right_index=True)
# 填充缺失值
merged_df.fillna(method='ffill', inplace=True)
print(merged_df)
输出结果为:
数值1 数值2
日期
2020-01-01 1.0 4.0
2020-01-02 2.0 4.0
2020-01-03 2.0 5.0
2020-01-04 2.0 5.0
2020-01-05 3.0 5.0
2020-01-06 3.0 6.0
在示例中,我们首先使用pd.to_datetime()
将日期列转换为日期时间类型,并将其设置为索引。然后使用merge()
函数将两个数据框按照索引进行合并,使用how='outer'
表示使用外连接,即保留两个数据框的所有日期。最后使用fillna()
函数将缺失值填充为最近的非缺失值。
下一篇:按最接近的值对字典进行排序