You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何合并字典中带日期索引的DataFrame列生成单一DataFrame?

问题:合并字典中带日期索引的DataFrame列成单一DataFrame

我有一个字典,其中每个键对应一个带有日期范围索引的DataFrame列。请问如何将字典中所有键对应的内容合并,得到一个包含所有列的单一DataFrame?

示例输入字典中的DataFrame:

# 键A对应的DataFrame
              apples
2020-01-01        2
2020-01-02        3
2020-01-03        4
2020-01-04        4

# 键B对应的DataFrame
              bananas
2020-01-01        8
2020-01-02        10
2020-01-03        7
2020-01-04        8

# 键C对应的DataFrame
              carrots
2020-01-01        9
2020-01-02        2
2020-01-03        3
2020-01-04        3

期望合并后的DataFrame:

apples     bananas     carrots
2020-01-01        2          8           9
2020-01-02        3          10          2
2020-01-03        4          7           3
2020-01-04        4          8           3
解决方案

直接使用pandas的pd.concat()方法,将字典中的所有DataFrame按列拼接即可,所有DataFrame的日期索引会自动对齐。

代码示例:

假设你的字典名为df_dict,执行以下代码:

import pandas as pd

merged_df = pd.concat(df_dict.values(), axis=1)

说明:

  • df_dict.values():提取字典内所有的DataFrame对象
  • axis=1:指定按列方向拼接(默认axis=0是按行拼接)
  • 若存在索引不匹配的情况,拼接后对应位置会填充NaN;你的示例中索引完全一致,会直接得到完整的合并结果。

内容的提问来源于stack exchange,提问作者Roxanne

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 10:36:28