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

Python Pandas条件聚合计算咨询:按时间范围、价格阈值对volume求和

Pandas 条件聚合实现方案

原始数据集

volumepricetime
10032021-09-29 04:00:00
30022021-09-29 05:30:00
70052021-09-29 06:00:00
50092021-09-29 06:30:00
900222021-09-29 07:00:00
400292021-09-29 07:30:00

实现代码

import pandas as pd

# 构造数据集
data = {
    "volume": [100, 300, 700, 500, 900, 400],
    "price": [3, 2, 5, 9, 22, 29],
    "time": [
        "2021-09-29 04:00:00",
        "2021-09-29 05:30:00",
        "2021-09-29 06:00:00",
        "2021-09-29 06:30:00",
        "2021-09-29 07:00:00",
        "2021-09-29 07:30:00"
    ]
}
df = pd.DataFrame(data)
# 转换时间字段为datetime类型,避免字符串比较异常
df["time"] = pd.to_datetime(df["time"])

# 需求1:时间范围筛选后求volume总和
start = pd.to_datetime("2021-09-29 05:45:00")
end = pd.to_datetime("2021-09-29 07:15:00")
sum_time = df[(df["time"] >= start) & (df["time"] <= end)]["volume"].sum()
print(sum_time) # 输出2100

# 需求2:price大于20的记录求volume总和
sum_price = df[df["price"] > 20]["volume"].sum()
print(sum_price) # 输出1300

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 18:27:03