如何按指定规则完成DataFrame多列缺失/切换值插值及同ID行合并
Python实现自定义零值插值与ID行合并
前置依赖
需要提前安装pandas和numpy库,导入方式如下:
import pandas as pd import numpy as np
步骤1:构造示例数据
df = pd.DataFrame({ 'ID': ['A', 'B', 'B', 'C'], 'Month1': [10, 15, 0, 0], 'Month2': [20, 32, 0, 100], 'Month3': [0, 0, 45, 0], 'Month4': [50, 0, 51, 400], 'Month5': [25, 0, 60, 150] }) # 提取所有月份列名方便后续批量处理 month_cols = [col for col in df.columns if 'Month' in col]
步骤2:合并同ID多行列(处理B类场景)
相同ID的两行数据月份列零值互补,直接按ID分组取各列最大值即可完成零值填充:
df_merged = df.groupby('ID', as_index=False)[month_cols].max()
步骤3:单行零值自定义插值(处理A、C类场景)
按照给定公式遍历处理每行的零值,代码如下:
def row_interpolate(row): val_list = row[month_cols].astype(float).tolist() length = len(val_list) for idx in range(length): # 跳过首位、末两位的零值(无有效前后值满足计算规则) if val_list[idx] != 0 or idx == 0 or idx >= length - 2: continue # 按要求计算插值 prev = val_list[idx-1] next1 = val_list[idx+1] next2 = val_list[idx+2] current_val = prev / (next2 + prev) * next1 val_list[idx] = round(current_val, 2) val_list[idx+1] = round(next1 - current_val, 2) row[month_cols] = val_list return row df_result = df_merged.apply(row_interpolate, axis=1)
输出结果
运行后打印df_result即可得到预期的输出:
| ID | Month1 | Month2 | Month3 | Month4 | Month5 |
|---|---|---|---|---|---|
| A | 10 | 20 | 17.77 | 32.23 | 25 |
| B | 15 | 32 | 45 | 51 | 60 |
| C | 0 | 100 | 160 | 240 | 150 |
内容的提问来源于stack exchange,提问作者Michael Itchon Gonzalez
相关产品推荐
相关产品推荐

