You need to enable JavaScript to run this app. 如何按指定规则完成DataFrame多列缺失/切换值插值及同ID行合并
优惠活动
大模型
产品
解决方案
定价
更多

如何按指定规则完成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即可得到预期的输出:

IDMonth1Month2Month3Month4Month5
A102017.7732.2325
B1532455160
C0100160240150

内容的提问来源于stack exchange,提问作者Michael Itchon Gonzalez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 11:06:09