Python 数据帧内插多索引
我需要插入多索引数据帧:Python 数据帧内插多索引,python,python-3.x,pandas,interpolation,Python,Python 3.x,Pandas,Interpolation,我需要插入多索引数据帧: 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 例如: def pd_interpolate_MI (df_input, df_toInterpolate): from scipy.inte
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
例如:
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()
这是主数据帧:
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系列
分别为每个索引
如你所见。这似乎是一种非常低效的方法
如果有人能充实我,我会很高兴
附言。
我花了一些时间仔细查看,如果答案在那里,我就错过了:
算法:
第一阶段:
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
第三阶段:
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
你可以用它来做你想做的事。如果数据帧是列为“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()
然后,例如使用df
和df_toI=pd.DataFrame(index=pd.MultiIndex.from_元组([(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
每个阶段意味着什么?你说需要为“1.3 1.7 1.55”找到结果是什么意思?我写下的阶段是我目前解决问题的方法。第四列是第一列中三列的实际值。把它想象成4D函数。。。f(x,y,z)=w