gpt4 book ai didi

python - 在 pandas 数据帧中插入多索引

转载 作者:行者123 更新时间:2023-12-02 06:40:29 26 4
gpt4 key购买 nike

我需要插入多索引数据帧:

例如:

这是主数据框:

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    

到目前为止我一直在做的是在里面附加一个 pd.Series 和 NaN分别针对每个索引。

正如你所看到的。这似乎是一种非常低效的方法。

如果有人能让我充实,我会很高兴。

附注我花了一些时间查看 SO,如果答案就在那里,我错过了:

Fill multi-index Pandas DataFrame with interpolation

Resampling Within a Pandas MultiIndex

pandas multiindex dataframe, ND interpolation for missing values

Fill multi-index Pandas DataFrame with interpolation

算法:

第一阶段:

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

第二阶段:

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

最佳答案

您可以使用 scipy.interpolate.LinearNDInterpolator 做你想做的事。如果数据框是包含“a”、“b”和“c”列的 MultiIndex,则:

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]))

现在,如果您有包含所有元组(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

关于python - 在 pandas 数据帧中插入多索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53871674/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com