python - 通过添加行以不同的增量对 Pandas DataFrame 进行插值

标签 python pandas interpolation

所以,基本上,我有一个如下所示的 DataFrame:

Initial Dataframe

任务是以 0.1 步增加“深度”(添加新行),并相应地插入“值”。

它应该是这样的: (由于尺寸原因裁剪了下半部分)

Result Dataframe

这是我写的代码草稿:

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

df['Depth']= ... #make it here with increment 0.1
df['Value'] = df['Value'].interpolate(method=linear)
df['Name'] = ... #copy it for each empty row

df.to_csv('Interpolated values.csv')

最佳答案

这是一个解决方案,它允许您使用步长的任何变化插入值(假设步长正好落在整数之间)并且插值更灵活:

my_df_list = []
step = 0.1

for label, group in df.sort_values('Depth').groupby('Name'):

    # Create a lookup dictionary for interpolation lookup
    lookup_dict = {x[0]:x[1] for x in group[['Depth', 'Value']].values}
    
    # Use np.linespace because of the strictness of start and end values
    new_index = np.linspace(
        start = group['Depth'].min(),
        stop = group['Depth'].max(),
        num = int(1/step) * np.ptp(group['Depth']) + 1
    )
    new_values = pd.Series(
        lookup_dict.get(round(x, 1)) for x in new_index
    ).interpolate()

    # Create a tmp df with your values
    df_tmp = pd.DataFrame.from_dict({
        'Name': [label] * len(new_index),
        'Depth': new_index, 
        'Value':new_values
    })
    my_df_list.append(df_tmp)

# Finally, combine all dfs
df_final = pd.concat(my_df_list, ignore_index=True)
    Name    Depth   Value
0   AS      15.0    100.0
1   AS      15.1    110.0
...
19  AS      16.9    290.0
20  AS      17.0    300.0
21  DB      10.0    200.0
22  DB      10.1    210.0
...
39  DB      11.8    380.0
40  DB      11.9    390.0
41  DB      12.0    400.0

关于python - 通过添加行以不同的增量对 Pandas DataFrame 进行插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69272076/

相关文章:

python - 在 Python 字典中访问同级字典值的最有效方法是什么?

python - 如果我是 Python 新手,我应该使用哪个版本的 Python?

python - 比较单个图 python 上的多年数据

python - Pandas DataFrame 到嵌套 JSON 而不更改数据结构

python - 欺诈检测分类ML的经纬度转换

python - 在所有 Pandas DataFrame 列和过滤器中搜索字符串

c - 我的二维插值 C 代码有什么问题

xcode - 在两点之间移动 UIButton 的正确方法?

matlab - 拉格朗日插值法

python - 将 Matlab fft2 衍射示例转换为 Python