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

如何用Pandas计算特定标签下最近7天的小时级cumulativeVol平均值?

仅用Pandas即可实现,无需自定义方法

完全可以通过Pandas内置方法完成需求,具体步骤如下(假设你的DataFrame索引为datetime类型,包含cumulativeVol和tag列):

步骤1:提取日期与小时字段

从时间索引中拆分出日期和小时,方便后续分组筛选:

df['date'] = df.index.date
df['hour'] = df.index.hour

步骤2:筛选指定标签的数据

先过滤出标签属于目标列表的记录:

target_tags = ['5f', '5i', '5j', '5x', '5h']
filtered_df = df[df['tag'].isin(target_tags)]

步骤3:获取最近7个符合条件的日期

提取所有带目标标签的唯一日期,按时间倒序后取最近7天:

# 去重得到所有符合条件的日期
unique_dates = filtered_df['date'].unique()
# 按时间从新到旧排序,取前7个
selected_dates = sorted(unique_dates, reverse=True)[:7]

步骤4:按小时计算平均值

用选中的7天数据,按小时分组求均值,最终得到24行1列的DataFrame:

result = filtered_df[filtered_df['date'].isin(selected_dates)] \
          .groupby('hour')['cumulativeVol'] \
          .mean() \
          .to_frame(name='avg_cumulativeVol')

补充说明

  • 如果你的DataFrame索引不是datetime类型,需要先转换:df.index = pd.to_datetime(df.index)
  • 若符合条件的日期不足7天,代码会自动取所有可用日期计算均值
  • 最终结果的索引为0-23的小时数,对应一天24小时的平均累计仓位

内容的提问来源于stack exchange,提问作者K.Best

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 16:27:38