如何在Pandas中按date列匹配将df_2的Volume列复制到df_1?
解决方案:遍历df_1匹配赋值
步骤1:初始化目标列
先给df_1新增一个空的Volume列,用于存储匹配后的数据:
import pandas as pd # 示例数据(可替换为你的实际DataFrame) df_1 = pd.DataFrame({ 'date': ['2023-01-01', '2023-01-02', '2023-01-03'], 'other_col': [100, 200, 300] }) df_2 = pd.DataFrame({ 'date': ['2023-01-01', '2023-01-03', '2023-01-04'], 'Volume': [5000, 7000, 9000] }) # 初始化Volume列为缺失值 df_1['Volume'] = pd.NA
步骤2:遍历df_1匹配赋值
方法1:直接遍历筛选(适合小数据量)
用itertuples()遍历df_1,逐行匹配df_2的date并赋值:
for row in df_1.itertuples(): # 筛选df_2中date匹配的行 match_row = df_2[df_2['date'] == row.date] if not match_row.empty: # 取第一个匹配的Volume值(若有多个匹配可按需调整) df_1.at[row.Index, 'Volume'] = match_row['Volume'].iloc[0]
方法2:字典映射提速(适合大数据量)
先把df_2转成date到Volume的映射字典,避免每次遍历都重复筛选,提升效率:
# 构建date-Volume映射字典(假设df_2中date唯一) volume_dict = df_2.set_index('date')['Volume'].to_dict() # 遍历赋值 for row in df_1.itertuples(): # 用get方法,匹配不到则保留缺失值 df_1.at[row.Index, 'Volume'] = volume_dict.get(row.date, pd.NA)
最终效果
处理后df_1的结果:
date other_col Volume 0 2023-01-01 100 5000.0 1 2023-01-02 200 NaN 2 2023-01-03 300 7000.0
内容的提问来源于stack exchange,提问作者John David Deatherage
相关产品推荐
相关产品推荐

