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

如何使用Pandas将数值拆分为多级分层类别实现阶梯计费计算

阶梯停放天数拆分与费用计算 Pandas 实现方案

核心逻辑适配任意数量的收费层级,无需硬编码层级数量,仅需保证阈值列命名遵循 tier.X.threshold 格式即可。

代码实现

1. 构造示例原始数据

你可以替换为自己的实际数据源:

import pandas as pd

raw_data = {
    "days": [11, 3, 7, 7],
    "tier.1.threshold": [5, 5, 5, 3],
    "tier.2.threshold": [5, 5, 5, 3],
    "tier.3.threshold": [pd.NA, pd.NA, pd.NA, pd.NA]
}
df = pd.DataFrame(raw_data)

2. 批量计算各层级停放天数

def calc_tier_days(row):
    total_days = row["days"]
    # 自动识别所有阈值列,按层级序号升序排列
    threshold_cols = sorted([c for c in row.index if c.endswith(".threshold")])
    tier_day_map = {}
    used_days = 0
    for tier_idx, col in enumerate(threshold_cols, 1):
        current_threshold = row[col]
        remaining_days = total_days - used_days
        if pd.isna(current_threshold):
            # 最后一层无上限,剩余天数全部计入当前层
            tier_day_map[f"tier.{tier_idx}.days"] = max(0, remaining_days)
        else:
            current_days = max(0, min(remaining_days, current_threshold))
            tier_day_map[f"tier.{tier_idx}.days"] = current_days
            used_days += current_days
    return pd.Series(tier_day_map)

# 合并计算结果到原表
df = pd.concat([df, df.apply(calc_tier_days, axis=1)], axis=1)

3. 计算各层级费用

按需配置层级费率后批量计算即可:

# 层级费率配置,可根据实际需求修改
tier_rate_config = {
    1: 0,   # 第一阶免费
    2: 50,  # 第二阶50美元/天
    3: 75   # 第三阶75美元/天
}

for tier_num, rate in tier_rate_config.items():
    df[f"tier.{tier_num}.charge"] = df[f"tier.{tier_num}.days"] * rate

# 可选:计算总费用
df["total_charge"] = df.filter(regex=r"tier\.\d+\.charge").sum(axis=1)

输出验证

执行完上述代码后,得到的tier.X.days字段完全符合你给出的示例结果,后续如果新增层级,仅需要在原始表新增对应阈值列、在费率配置里加对应层级的费率即可,无需修改核心计算逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 04:27:00