双向插值的替代方法

问题描述 投票:2回答:1

我编写了一些代码,根据两个标准(保险金额和自付额百分比)执行插值。我正在努力一次全部进行插值,因此拆分了过滤。表hf包含了我用来作为插值结果基础的已知数据。表df包含了需要根据hf进行插值的已开发因子的新数据。

现在,我的解决方法是首先根据ded_amount百分比过滤每个表,然后将其插入到空数据帧中,并在每个循环之后追加。

我觉得这效率低下,有一种更好的方法可以执行此操作,希望听到一些有关我可以做出的改进的反馈。谢谢

下面提供测试数据。

import pandas as pd
from scipy import interpolate

known_data={'AOI':[80000,100000,150000,200000,300000,80000,100000,150000,200000,300000],'Ded_amount':['2%','2%','2%','2%','2%','3%','3%','3%','3%','3%'],'factor':[0.797,0.774,0.739,0.733,0.719,0.745,0.737,0.715,0.711,0.709]}
new_data={'AOI':[85000,120000,130000,250000,310000,85000,120000,130000,250000,310000],'Ded_amount':['2%','2%','2%','2%','2%','3%','3%','3%','3%','3%']}

hf=pd.DataFrame(known_data)
df=pd.DataFrame(new_data)

deduct_fact=pd.DataFrame()
for deduct in hf['Ded_amount'].unique():
    deduct_table=hf[hf['Ded_amount']==deduct]
    aoi_table=df[df['Ded_amount']==deduct]
    x=deduct_table['AOI']
    y=deduct_table['factor']
    f=interpolate.interp1d(x,y,fill_value="extrapolate")
    xnew=aoi_table[['AOI']]
    ynew=f(xnew)
    append_frame=aoi_table
    append_frame['Factor']=ynew
    deduct_fact=deduct_fact.append(append_frame)
python scipy interpolation
1个回答
2
投票

是的,有一种方法可以更有效地执行此操作,而不必制作一堆中间数据帧并附加它们。看一下这段代码:

from scipy import interpolate
known_data={'AOI':[80000,100000,150000,200000,300000,80000,100000,150000,200000,300000],'Ded_amount':['2%','2%','2%','2%','2%','3%','3%','3%','3%','3%'],'factor':[0.797,0.774,0.739,0.733,0.719,0.745,0.737,0.715,0.711,0.709]}
new_data={'AOI':[85000,120000,130000,250000,310000,85000,120000,130000,250000,310000],'Ded_amount':['2%','2%','2%','2%','2%','3%','3%','3%','3%','3%']}

hf=pd.DataFrame(known_data)
df=pd.DataFrame(new_data)

# Create this column now
df['Factor'] = None

# I like specifying this explicitly; easier to debug
deduction_amounts = list(hf.Ded_amount.unique())
for deduction_amount in deduction_amounts:
    # You can index a dataframe and call a column in one line
    x, y = hf[hf['Ded_amount']==deduction_amount]['AOI'], hf[hf['Ded_amount']==deduction_amount]['factor']

    f = interpolate.interp1d(x, y, fill_value="extrapolate")

    # This is the most important bit. Lambda function on the dataframe
    df['Factor'] = df.apply(lambda x: f(x['AOI']) if x['Ded_amount']==deduction_amount else x['Factor'], axis=1)

lambda函数的工作方式是:它逐行通过“因子”列,并根据其他列上的条件为其提供值。

如果扣除额匹配,它将返回df的AOI列的内插值(这就是您所说的xnew,否则,它只会返回相同的内容。

© www.soinside.com 2019 - 2024. All rights reserved.