如何基于DataFrame的start_month和close_month生成open_xxxx哑变量列
生成基于月份区间的哑变量列解决方案
问题描述
现有如下结构的DataFrame:
| case_id | start_month | close_month |
|---|---|---|
| A01 | 2023-02 | 2023-03 |
| A02 | 2023-02 | 2023-05 |
| A03 | 2023-03 | 2023-04 |
| A04 | 2023-03 | 2023-05 |
| A05 | 2023-04 | 2023-05 |
需要生成格式为open_xxxxxx(如open_202302、open_202303)的哑变量列,取值规则:
- 案例在
close_month的前一个月及之前处于开放状态时,对应月份列值为1,否则为0 - 示例:若
start_month为2023-03、close_month为2023-05,则open_202303和open_202304的值为1
期望输出结果:
| case_id | start_month | close_month | open_202302 | open_202303 | open_202304 | open_202305 |
|---|---|---|---|---|---|---|
| A01 | 2023-02 | 2023-03 | 1 | 0 | 0 | 0 |
| A02 | 2023-02 | 2023-05 | 1 | 1 | 1 | 0 |
| A03 | 2023-03 | 2023-04 | 0 | 1 | 0 | 0 |
| A04 | 2023-03 | 2023-05 | 0 | 1 | 1 | 0 |
| A05 | 2023-05 | 2023-05 | 0 | 0 | 0 | 0 |
解决方案
步骤1:转换日期格式并生成目标月份列名
先将月份列转为周期类型(保留月份精度),再提取所有需要生成的哑变量列名:
import pandas as pd # 构造输入DataFrame df = pd.DataFrame({ 'case_id': ['A01', 'A02', 'A03', 'A04', 'A05'], 'start_month': ['2023-02', '2023-02', '2023-03', '2023-03', '2023-04'], 'close_month': ['2023-03', '2023-05', '2023-04', '2023-05', '2023-05'] }) # 转换为月份周期类型 df['start_month'] = pd.to_datetime(df['start_month']).dt.to_period('M') df['close_month'] = pd.to_datetime(df['close_month']).dt.to_period('M') # 生成所有目标月份的列名 all_months = pd.period_range(start=df['start_month'].min(), end=df['close_month'].max(), freq='M') month_columns = [f'open_{m.strftime("%Y%m")}' for m in all_months]
步骤2:批量生成哑变量列
通过广播比较每个案例的月份区间与目标月份,生成1/0值:
for col in month_columns: # 提取列名中的目标月份 target_month = pd.Period(col.split('_')[1], freq='M') # 判定条件:目标月份在start_month(含)到close_month(不含)之间 df[col] = ((df['start_month'] <= target_month) & (target_month < df['close_month'])).astype(int)
步骤3:查看结果
执行后直接输出df即可得到预期结果:
print(df)
该方法避免了低效的循环,利用Pandas的向量化操作提升处理效率,适配大规模数据集场景。
内容的提问来源于stack exchange,提问作者Sang Nguyen
相关产品推荐
相关产品推荐

