如何将pandas DataFrame中SHILLER值按日期匹配添加到另一DataFrame
解决方案
你可以直接用pandas的merge方法完成匹配,以下提供两种常用场景的实现代码:
场景1:严格按日期精确匹配,仅SHILLER发布当天填充对应值
首先统一两个DataFrame的日期列格式为datetime类型,避免字符串格式不匹配导致的匹配失败,再通过左连接保留所有OHLC日线数据,匹配到SHILLER值的行自动填充:
import pandas as pd # 假设SHILLER值表名为df_shiller,OHLC日线表名为df_ohlc,日期列名均为date # 统一日期格式 df_shiller['date'] = pd.to_datetime(df_shiller['date']) df_ohlc['date'] = pd.to_datetime(df_ohlc['date']) # 左连接合并,仅引入SHILLER字段 df_ohlc = df_ohlc.merge( df_shiller[['date', 'SHILLER']], on='date', how='left' )
场景2:按月度匹配,当月所有交易日都填充当月发布的SHILLER值
针对SHILLER这类月更指标,更常用的是把月度值填充到当月所有交易日,实现方式如下:
import pandas as pd # 统一日期格式 df_shiller['date'] = pd.to_datetime(df_shiller['date']) df_ohlc['date'] = pd.to_datetime(df_ohlc['date']) # 生成临时年月字段用于匹配 df_shiller['year_month'] = df_shiller['date'].dt.to_period('M') df_ohlc['year_month'] = df_ohlc['date'].dt.to_period('M') # 合并后删除临时年月字段 df_ohlc = df_ohlc.merge( df_shiller[['year_month', 'SHILLER']], on='year_month', how='left' ).drop('year_month', axis=1)
如果两个表的日期列命名不同,把on='date'替换为left_on='OHLC表的日期列名', right_on='SHILLER表的日期列名'即可。
内容的提问来源于stack exchange,提问作者ShamedSoul
相关产品推荐
相关产品推荐

