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

如何合并不同时间索引的Pandas Series并计算对应总和?

合并不同Datetime索引的Pandas Series并计算总和

我尝试合并两个带有不同datetime索引的pandas.Series,但没法得到正确结果。见过把两个Series存入DataFrame的方案,但希望返回一个包含两者总和的单个Series。

背景:我有记录房间内检测人数的pandas Series,想要合并为整栋楼的人数统计(示例是2个房间),需要聚合所有房间数据。我觉得得先排序Series再逐行处理,但现在用zip()遍历已排序的Series,怀疑有更优方法,求建议?

原数据代码

import pandas as pd

# 房间1数据
room1_idx = pd.to_datetime([
    '2023-08-11T17:00:44',  # 6人
    '2023-08-11T17:06:47',  # 7人
    '2023-08-11T17:06:49',  # 8人
    '2023-08-11T17:07:00',  # 10人
    '2023-08-11T17:07:20',  # 8人
])
room1 = pd.Series([6, 7, 8, 10, 8], index=room1_idx, name="Room 1")

# 房间2数据
room2_idx = pd.to_datetime([
    '2023-08-11T17:06:45',  # 1人
    '2023-08-11T17:06:46',  # 4人
    '2023-08-11T17:06:47',  # 5人
    '2023-08-11T17:07:02',  # 10人
    '2023-08-11T17:07:10',  # 7人
    '2023-08-11T17:07:30',  # 2人
])
room2 = pd.Series([1, 4, 5, 10, 7, 2], index=room2_idx, name="Room 2")

print(room1)
print(room2)

期望输出

building_idx = pd.to_datetime([
    '2023-08-11 17:00:44',  # 6+0人
    '2023-08-11 17:06:45',  # 6+1人
    '2023-08-11 17:06:46',  # 6+4人
    '2023-08-11 17:06:47',  # 7+5人
    '2023-08-11 17:06:49',  # 8+5人
    '2023-08-11 17:07:00',  # 10+5人
    '2023-08-11 17:07:02',  # 10+10人
    '2023-08-11 17:07:10',  # 10+7人
    '2023-08-11 17:07:20',  # 8+7人
    '2023-08-11 17:07:30',  # 9+2人(注:实际应为8+2=10,此处可能为笔误)
])
building = pd.Series([6, 7, 10, 12, 13, 15, 20, 17, 15, 11], index=building_idx, name="Building")
print(building)

最优解决方案

不需要手动遍历,利用Pandas的内置方法就能高效完成需求,核心思路是将两个Series对齐到统一的时间索引,用前向填充保留最近的人数数据,再求和:

# 获取所有时间点的并集并排序
all_times = room1.index.union(room2.index).sort_values()

# 重新索引并填充缺失值:前向填充保留最近的人数,初始缺失用0填充
room1_filled = room1.reindex(all_times).ffill().fillna(0)
room2_filled = room2.reindex(all_times).ffill().fillna(0)

# 计算整栋楼人数总和,转为整数并重命名
building = (room1_filled + room2_filled).astype(int).rename("Building")

print(building)

输出结果

2023-08-11 17:00:44     6
2023-08-11 17:06:45     7
2023-08-11 17:06:46    10
2023-08-11 17:06:47    12
2023-08-11 17:06:49    13
2023-08-11 17:07:00    15
2023-08-11 17:07:02    20
2023-08-11 17:07:10    17
2023-08-11 17:07:20    15
2023-08-11 17:07:30    10
Name: Building, dtype: int64

方案优势

  • 避免手动遍历,代码简洁易维护
  • 利用Pandas的矢量化运算,处理大规模数据时效率远高于循环遍历
  • 自动处理时间索引的排序和对齐,无需手动管理顺序

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 13:52:05