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

如何按日期合并多列不同的Pandas时间序列DataFrame并求和

问题需求

我有数百个时间序列Pandas DataFrame,每个代表不同对象,都包含dates列和一个无用索引列,其余数据列存在差异(有的包含全部列,有的包含部分列,有的完全没有)。需要按dates列合并这些DataFrame,对同名数据列求和,最终得到包含所有列、按日期聚合求和的结果(全NaN的单元格保留NaN)。

示例数据

DF#1

indexdates10001001100210121014
02023-01-311NaN111
12023-02-01111011
22023-02-0212NaN11
32023-02-0323111
42023-02-04231NaN1
52023-02-0533111
62023-02-0644111
72023-02-0745111

DF#2

indexdates10001001100310062001
02023-01-311NaN111
12023-02-01111011
22023-02-0212NaN11
32023-02-0323111
42023-02-04231NaN1
52023-02-053NaN111
62023-02-0644111
72023-02-0745111

DF#3

indexdates10001001100310121014
02023-01-3111111
12023-02-011NaN1011
22023-02-0212NaN11
32023-02-0323111
42023-02-04231NaN1
52023-02-0533111
62023-02-0644111
72023-02-07451NaN1

期望结果DF

indexdates10001001100210031006101210142001
02023-01-3131121221
12023-02-013210201221
22023-02-0236NaNNaN1221
32023-02-0369121221
42023-02-046912NaNNaN22
52023-02-0596121221
62023-02-061212121221
72023-02-071215121121
解决方案

步骤说明

  1. 移除所有DataFrame中的无用索引列;
  2. 拼接所有DataFrame,保留所有列,缺失值补NaN;
  3. 按dates列分组,对每列求和(若该日期下该列全为NaN则保留NaN,否则求和非NaN值);
  4. 重置索引并调整列顺序以匹配期望结果。

代码实现

import pandas as pd
import numpy as np

# 假设所有DataFrame存储在列表dfs中,例如:dfs = [df1, df2, df3]
# 第一步:移除无用索引列
for df in dfs:
    df.drop('index', axis=1, inplace=True)

# 第二步:拼接所有DataFrame
combined = pd.concat(dfs, ignore_index=True)

# 第三步:按dates分组聚合,自定义求和逻辑
result = combined.groupby('dates', as_index=False).agg(
    lambda x: x.sum(skipna=True) if x.notna().any() else np.nan
)

# 第四步:重置索引并调整列顺序
result.reset_index(drop=False, inplace=True)
# 按期望结果的列顺序调整
column_order = ['index', 'dates', '1000', '1001', '1002', '1003', '1006', '1012', '1014', '2001']
result = result[column_order]

代码说明

  • pd.concat会自动合并所有列,不存在的列填充NaN,完美适配列不统一的场景;
  • 自定义聚合函数确保:当某日期下某列的所有值都是NaN时,结果保留NaN;否则对所有非NaN值求和,符合预期结果要求;
  • 最后调整列顺序是为了和示例期望结果完全一致,若不需要严格顺序可省略该步骤。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 16:19:53