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

基于Pandas DataFrame实现月度自动天数适配的计算函数开发

解决Pandas自动适配当月天数计算Output_Value的方案

核心思路

  1. 自动获取当月天数:利用Pandas的dt.days_in_month属性,直接从extracted_date字段提取对应月份的天数,替代手动输入的固定值。
  2. 按区间计算Output_Value:保留原有的value区间逻辑,将固定天数替换为自动获取的当月天数,用向量化方法实现高效计算。

具体实现步骤

1. 确保日期字段为datetime类型

如果extracted_date还不是datetime格式,先转换:

df['extracted_date'] = pd.to_datetime(df['extracted_date'])

2. 新增当月天数字段

添加一列存储每个日期对应的当月天数:

df['month_days'] = df['extracted_date'].dt.days_in_month

3. 按value区间计算Output_Value

假设原逻辑为:

  • 当value < 100:Output_Value = value * 当月天数 * 0.8
  • 当100 ≤ value < 200:Output_Value = value * 当月天数 * 1.0
  • 当value ≥ 200:Output_Value = value * 当月天数 * 1.2

用np.select实现向量化计算(比apply更高效):

import numpy as np

# 定义条件和对应计算式
conditions = [
    df['value'] < 100,
    (df['value'] >= 100) & (df['value'] < 200),
    df['value'] >= 200
]

calculations = [
    df['value'] * df['month_days'] * 0.8,
    df['value'] * df['month_days'] * 1.0,
    df['value'] * df['month_days'] * 1.2
]

# 生成Output_Value列
df['Output_Value'] = np.select(conditions, calculations, default=np.nan)

验证方法

可以手动构造不同月份的测试数据,比如:

test_data = pd.DataFrame({
    'extracted_date': ['2024-02-15', '2024-04-20', '2024-01-10'],
    'value': [80, 150, 250]
})

运行代码后,month_days会分别返回29(2024年是闰年)、30、31,对应的Output_Value也会自动适配这些天数计算。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 03:45:55