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

基于死亡时间提取个体死前0-12个月消费数据并重构DataFrame的技术咨询

问题:提取个体死亡前0-12个月的消费数据

我正在分析个体死亡前的消费模式,手头的数据集包含个体的月度消费数据以及他们的死亡日期,示例格式如下:

ID 2018_11 2018_12 2019_01 2019_02 2019_03 2019_04 2019_05 2019_06 2019_07 2019_08 2019_09 2019_10 2019_11 2019_12 2020_01 date_of_death
A 15 14 6 23 23 5 6 30 1 15 6 7 8 30 1 2020-01-02
B 2 5 6 7 7 8 9 15 12 14 31 30 31 0 0 2019-11-15

每一列的YYYY_MM格式代表对应年月,单元格数字是该月消费金额。我需要构建一个新的DataFrame,包含每个个体死亡前0-12个月的消费数据,目标格式如下:

ID last_12_month last_11_month ...... last_1_month last_0_month date_of_death
A 6 23 ...... 30 1 2020-01-02
B 2 5 ...... 30 31 2019-11-15

规则是:

  • 个体A于2020-01-02死亡,last_0_month对应2020_01列,last_12_month对应2019_01列;
  • 个体B于2019-11-15死亡,last_0_month对应2019_11列,last_12_month对应2018_11列。

恳请提供技术实现的帮助。


解决方案(基于Python Pandas)

这是典型的时间序列数据定向提取问题,用Pandas可以很优雅地实现需求,下面是具体的步骤和代码:

步骤1:数据预处理

首先把死亡日期列转换成datetime类型,方便后续的日期计算,避免字符串操作的麻烦:

import pandas as pd

# 加载你的数据集(这里用示例数据演示,实际替换成你的数据加载代码即可)
data = pd.DataFrame({
    'ID': ['A', 'B'],
    '2018_11': [15, 2],
    '2018_12': [14, 5],
    '2019_01': [6, 6],
    '2019_02': [23, 7],
    '2019_03': [23, 7],
    '2019_04': [5, 8],
    '2019_05': [6, 9],
    '2019_06': [30, 15],
    '2019_07': [1, 12],
    '2019_08': [15, 14],
    '2019_09': [6, 31],
    '2019_10': [7, 30],
    '2019_11': [8, 31],
    '2019_12': [30, 0],
    '2020_01': [1, 0],
    'date_of_death': ['2020-01-02', '2019-11-15']
})

# 转换死亡日期为datetime类型
data['date_of_death'] = pd.to_datetime(data['date_of_death'])

步骤2:逐行提取目标消费数据

定义一个函数,针对每个个体计算出死亡前0-12个月对应的年月列,然后提取这些列的数值,并整理成目标格式的字段:

def extract_pre_death_consumption(row):
    # 生成从last_12到last_0对应的年月列名
    target_month_cols = []
    for months_back in range(12, -1, -1):
        # 计算往前推months_back个月的日期
        target_date = row['date_of_death'] - pd.DateOffset(months=months_back)
        # 格式化为YYYY_MM的列名格式
        col_name = f"{target_date.year}_{target_date.month:02d}"
        target_month_cols.append(col_name)
    
    # 提取对应列的消费值
    consumption_values = row[target_month_cols].tolist()
    # 构建结果字典,映射到last_n_month的字段名
    result_dict = {
        f'last_{12 - idx}_month': val 
        for idx, val in enumerate(consumption_values)
    }
    # 保留ID和死亡日期
    result_dict['ID'] = row['ID']
    result_dict['date_of_death'] = row['date_of_death']
    
    return pd.Series(result_dict)

# 应用函数到每一行,生成新的DataFrame
new_df = data.apply(extract_pre_death_consumption, axis=1)

步骤3:调整列顺序(可选)

如果需要把ID和死亡日期放在最前面,可以调整列的顺序,让结果更符合你的预期:

# 定义目标列顺序:ID → last_12到last_0 → date_of_death
target_columns = ['ID'] + [f'last_{n}_month' for n in range(12, -1, -1)] + ['date_of_death']
new_df = new_df[target_columns]

最终结果

运行完上述代码后,new_df就是你需要的格式,示例输出如下:

ID  last_12_month  last_11_month  last_10_month  last_9_month  last_8_month  last_7_month  last_6_month  last_5_month  last_4_month  last_3_month  last_2_month  last_1_month  last_0_month date_of_death
0  A              6             23             23             5             6            30             1            15             6             7             8            30             1    2020-01-02
1  B              2              5              6              7              7             8             9            15            12            14            31            30            31    2019-11-15

关键细节说明

  • 用pd.DateOffset计算日期,能自动处理跨年、跨月的情况(比如1月往前推1个月会自动变成去年12月),比手动计算年月更可靠;
  • 逐行处理的方式确保每个个体都能匹配到自己对应的消费列,不会因为死亡时间不同而出错;
  • 代码结构清晰,你可以根据自己的实际需求调整字段名或者提取的月份范围(比如如果需要前6个月,只需要修改range(6, -1, -1)即可)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 15:54:07