插值多索引Pandas数据框。

4

我需要对多级索引的数据框进行插值:

例如:

这是主要的数据框:

a    b    c    result
1    1    1    6
1    1    2    9
1    2    1    8
1    2    2    11
2    1    1    7
2    1    2    10
2    2    1    9
2    2    2    12

我需要找到以下内容的结果:

1.3    1.7    1.55    

到目前为止,我一直在单独为每个索引附加一个带有NaN的pd.Series。正如您所看到的,这似乎是非常低效的方式。
如果有人能够丰富我的知识,我会很高兴。
附言:我花了一些时间在SO上查找,如果答案在那里,我错过了它: 使用插值填充多级索引Pandas DataFrame Pandas MultiIndex中的重新采样 pandas多级索引数据框,用于缺失值的ND插值 使用插值填充多级索引Pandas DataFrame 算法:
阶段1:
a    b    c    result
1    1    1    6
1    1    2    9
1    2    1    8
1    2    2    11
1.3    1    1    6.3
1.3    1    2    9.3
1.3    2    1    8.3
1.3    2    2    11.3
2    1    1    7
2    1    2    10
2    2    1    9
2    2    2    12

阶段2:
a    b    c    result
1    1    1    6
1    1    2    9
1    2    1    8
1    2    2    11
1.3    1    1    6.3
1.3    1    2    9.3
1.3    1.7    1    7.7
1.3    1.7    2    10.7
1.3    2    1    8.3
1.3    2    2    11.3
2    1    1    7
2    1    2    10
2    2    1    9
2    2    2    12

阶段3:
a    b    c    result
1    1    1    6
1    1    2    9
1    2    1    8
1    2    2    11
1.3    1    1    6.3
1.3    1    2    9.3
1.3    1.7    1    7.7
1.3    1.7    1.55    9.35
1.3    1.7    2    10.7
1.3    2    1    8.3
1.3    2    2    11.3
2    1    1    7
2    1    2    10
2    2    1    9
2    2    2    12

每个阶段的含义是什么?你所说的需要找到“1.3 1.7 1.55”的结果是什么意思? - Jessica
我写下的步骤是我目前解决问题的方法。第四列是前三列的实际值。将其想象为4D函数... f(x,y,z) = w。 - umn
1个回答

4
您可以使用 scipy.interpolate.LinearNDInterpolator 来实现您的需求。如果数据框是一个多重索引,包括列 'a'、'b' 和 'c',那么:
from scipy.interpolate import LinearNDInterpolator as lNDI
print (lNDI(points=df.index.to_frame().values, values=df.result.values)([1.3, 1.7, 1.55]))

现在如果你有一个DataFrame,其中所有元组 (a, b, c) 都是索引,你想要计算它们,可以执行以下操作:

def pd_interpolate_MI (df_input, df_toInterpolate):
    from scipy.interpolate import LinearNDInterpolator as lNDI
    #create the function of interpolation
    func_interp = lNDI(points=df_input.index.to_frame().values, values=df_input.result.values)
    #calculate the value for the unknown index
    df_toInterpolate['result'] = func_interp(df_toInterpolate.index.to_frame().values)
    #return the dataframe with the new values
    return pd.concat([df_input, df_toInterpolate]).sort_index()

例如,使用您的dfdf_toI = pd.DataFrame(index = pd.MultiIndex.from_tuples([(1.3, 1.7, 1.55),(1.7, 1.4, 1.9)],names = df.index.names)),然后您将得到

print (pd_interpolate_MI(df, df_toI))
              result
a   b   c           
1.0 1.0 1.00    6.00
        2.00    9.00
    2.0 1.00    8.00
        2.00   11.00
1.3 1.7 1.55    9.35
1.7 1.4 1.90   10.20
2.0 1.0 1.00    7.00
        2.00   10.00
    2.0 1.00    9.00
        2.00   12.00

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接