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

如何在Pandas DataFrame中按0.1步长新增Depth行并插值Value列

Pandas深度列步长扩展与数值插值实现方案

你可以直接使用下方补全后的可运行代码实现需求:

import pandas as pd
import numpy as np

df = pd.DataFrame({'Name': ['AS', 'AS', 'AS', 'DB', 'DB', 'DB'],
                   'Depth': [15, 16, 17, 10, 11, 12],
                   'Value': [100, 200, 300, 200, 300, 400]})

result_list = []
# 按Name分组独立处理,避免不同名称的深度区间互相干扰
for name, group_df in df.groupby('Name'):
    # 生成当前分组下从最小深度到最大深度、步长0.1的完整深度序列
    full_depth = np.arange(group_df['Depth'].min(), group_df['Depth'].max() + 0.1, 0.1)
    # 将Depth设为索引后重索引到完整深度序列
    temp_df = group_df.set_index('Depth').reindex(full_depth)
    # 线性插值填充Value列
    temp_df['Value'] = temp_df['Value'].interpolate(method='linear')
    # 填充当前分组的Name值
    temp_df['Name'] = name
    # 重置索引将Depth恢复为普通列
    result_list.append(temp_df.reset_index(names='Depth'))

# 合并所有分组的处理结果
final_df = pd.concat(result_list, ignore_index=True)
# 处理浮点精度问题,保留Depth一位小数
final_df['Depth'] = final_df['Depth'].round(1)

final_df.to_csv('Interpolated values.csv', index=False)

关键逻辑说明

  • 必须按Name字段分组处理:不同名称对应的深度区间独立,直接全局处理会出现跨名称的错误插值
  • np.arange生成深度序列时末尾加0.1,是为了将原数据的最大深度值也包含在新序列中
  • 重索引后自动生成的空值行通过线性插值填充数值,符合要求的平滑过渡效果
  • 对Depth做一位小数舍入,避免浮点运算出现15.1000000000001这类精度问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 11:39:03