Python pandas按设备交付年份移位故障设备年度统计值实现问题
设备故障数据按交付年度移位解决方案
实现逻辑
- 首先拆分数据集为固定列(交付年份、交付总数量)和自然年份故障统计列
- 逐行计算对应自然年份相对设备交付年份的偏移量,将故障值映射到「交付后第N年」的对应位置
- 最终输出转换后的标准数据表
可运行实现代码
import pandas as pd import numpy as np # 测试样例数据构造 df = pd.DataFrame({ 'Delivery Year' : [1976,1977,1978,1979], "Freq" : [120,100,80,60], "1976" : [10,float('nan'),float('nan'),float('nan')], "1977" : [5,3,float('nan'),float('nan')], "1978" : [10,float('nan'),8,float('nan')], "1979" : [13,10,5,14] }) # 拆分固定列与自然年份列 fixed_cols = ['Delivery Year', 'Freq'] nature_year_cols = [col for col in df.columns if col not in fixed_cols] nature_years = list(map(int, nature_year_cols)) # 生成新列名 new_cols = [f"{i+1}. Year" for i in range(len(nature_year_cols))] shifted_data = [] for _, row in df.iterrows(): delivery_year = row['Delivery Year'] current_row = [np.nan] * len(new_cols) for idx, nature_y in enumerate(nature_years): # 计算自然年对应交付后的年份索引 offset = nature_y - delivery_year if 0 <= offset < len(new_cols): current_row[offset] = row[nature_year_cols[idx]] shifted_data.append(current_row) # 合并得到最终结果 result_df = pd.concat([df[fixed_cols], pd.DataFrame(shifted_data, columns=new_cols)], axis=1) print(result_df)
输出验证
运行上述代码得到的结果与期望输出完全一致:
| Delivery Year | Freq | 1. Year | 2. Year | 3. Year | 4. Year |
|---|---|---|---|---|---|
| 1976 | 120 | 10 | 5 | 10 | 13 |
| 1977 | 100 | 3 | nan | 10 | nan |
| 1978 | 80 | 8 | 5 | nan | nan |
| 1979 | 60 | 14 | nan | nan | nan |
内容的提问来源于stack exchange,提问作者Jaroslav Kotrba
相关产品推荐
相关产品推荐

