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

Pandas时间序列按日重采样:仅全高于/低于阈值日返回均值

实现代码

首先确保你已经导入pandas库,且时间序列已设置为DataFrame的datetime索引:

import pandas as pd

# 阈值定义
THRESHOLD = 126.82

# 自定义按日聚合函数
def calc_daily_mean(series):
    all_above = (series > THRESHOLD).all()
    all_below = (series < THRESHOLD).all()
    if all_above or all_below:
        return round(series.mean(), 2)
    return pd.NA

# 执行聚合计算
result = df.resample("1d")["value"].apply(calc_daily_mean)
逻辑说明
  • 若未提前设置时间索引,需要先执行预处理:
    df["time"] = pd.to_datetime(df["time"])
    df = df.set_index("time")
    
  • 自定义函数中先对当日所有值做布尔校验,只有全部高于阈值或全部低于阈值时才计算均值,否则返回空值
  • 如果业务规则允许数值等于阈值的情况,将判断条件中的>修改为>=、<修改为<=即可适配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 16:54:05