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

如何用Pandas在指定时间段内计算最大金额总和?

用Pandas计算指定时间段内的最大金额总和

当然可以用Pandas实现这个需求,先明确逻辑:我们要找任意长度为80ms的时间区间,计算区间内所有amount的总和最大值。按你的数据,标准计算结果应为1600(所有数据都落在10ms到90ms的区间内,总和是200+300+100+1000=1600),如果你的预期结果1300是基于特定规则(比如仅取两个时间点的金额和),可以看后面的调整方案。

标准实现步骤:

  1. 导入库并构建DataFrame:
import pandas as pd
from pandas import DataFrame

df = DataFrame.from_records([
  {"time": 10, "amount": 200},
  {"time": 70, "amount": 1000},
  {"time": 10, "amount": 300},
  {"time": 10, "amount": 100},
])
  1. 按time排序(滑动窗口计算需要时间有序):
df_sorted = df.sort_values('time').reset_index(drop=True)
  1. 用双指针法高效计算最大窗口总和(避免重复计算,适合大数据量):
left = 0
max_total = 0
current_total = 0

for right in range(len(df_sorted)):
    current_total += df_sorted['amount'].iloc[right]
    # 当窗口时间差超过80ms时,移动左指针缩小窗口
    while df_sorted['time'].iloc[right] - df_sorted['time'].iloc[left] > 80:
        current_total -= df_sorted['amount'].iloc[left]
        left += 1
    # 更新最大总和
    if current_total > max_total:
        max_total = current_total

print(max_total)  # 输出1600

若预期结果1300是基于“两个时间点的最大金额和”规则:

比如要求选取时间差≤80ms的两个金额,取最大和,代码如下:

max_pair_sum = 0
for i in range(len(df_sorted)):
    for j in range(i+1, len(df_sorted)):
        if df_sorted['time'].iloc[j] - df_sorted['time'].iloc[i] <= 80:
            current_sum = df_sorted['amount'].iloc[i] + df_sorted['amount'].iloc[j]
            if current_sum > max_pair_sum:
                max_pair_sum = current_sum

print(max_pair_sum)  # 输出1300

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 06:00:59