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

Pandas DataFrame基于多时间区间条件取最大值创建新列的方法

实现代码

import pandas as pd

# 构造测试数据
df = pd.DataFrame({
    'weight': [[200, 190, 188, 180, 170], [181, 175, 172, 165, 150]],
    'days_since_gym': [[0, 87, 174, 205, 279], [93, 171, 241, 273, 300]]
})

# 配置区间规则:(左边界, 右边界, 列名),区间左右均包含
interval_config = [
    (0, 90, '0-90'),
    (91, 180, '91-180'),
    (181, 270, '181-270'),
    (271, 360, '271-360')
]

def calc_interval_max(row):
    # 配对当前行的天数和对应体重
    pairs = list(zip(row['days_since_gym'], row['weight']))
    result = []
    for low, high, _ in interval_config:
        # 筛选当前区间的体重
        match_weights = [w for d, w in pairs if low <= d <= high]
        result.append(max(match_weights) if match_weights else 0)
    return pd.Series(result, index=[col for _, _, col in interval_config])

# 批量生成新列
df[[col for _, _, col in interval_config]] = df.apply(calc_interval_max, axis=1)

print(df)

输出结果

weight           days_since_gym  0-90  91-180  181-270  271-360
0  [200, 190, 188, 180, 170]    [0, 87, 174, 205, 279]   200     188      180      170
1  [181, 175, 172, 165, 150]  [93, 171, 241, 273, 300]     0     181      172      165

方案说明

  • 所有区间规则统一在interval_config中维护,后续需要调整区间划分、列名时,仅修改该配置即可,无需改动核心逻辑
  • 单函数处理单行逻辑,可读性高,调试成本低
  • 兼容行内体重和天数长度不一致的边界情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 00:24:04