在Pandas数据帧上进行计算时,仅矢量化函数中的某些参数

时间:2018-11-19 21:38:05

标签: python pandas numpy dataframe vectorization

我编写了一个函数,该函数旨在基于其他两个列来计算新的数据框列,作为来自另一个数据框的几个数据点。我想将此功能以向量化的方式应用于主数据帧,以便以这种方式计算2列输入。同时,我希望第三个参数是用于单独插值计算(即未向量化)的常量数据帧。如何做到这一点?

主要功能(例如):

def calc_fitted_values(L, option, df_ref):
    '''
    This calculates an outputval for each combination of L and option, based
    on intermediate calculations involving fitted values from df_ref.
    - L is some column in my main dataframe
    - option is a second column in the main dataframe
    - df_ref is a separate data frame used in the pre-calculations here
    '''
    df_ref_option = df_ref[df_ref['option']==option]  # take slice of df_ref based on option
    x = df_ref_option['x'].values                         # get data columns to be used for polyfit
    y = df_ref_option['y'].values
    C = np.polyfit(np.log(x), np.log(y), 1);   # use polyfit to get log fit of the reference data
    a = np.exp(C[1]);
    b = C[0];  
    outputval = a*(L**b)
    return outputval

希望通过功能使用:

df['outputval']] = calc_fitted_values(df['L'], df['option'], df_ref)

在此示例中,Loption是从我的主数据帧列(df)中获得的数组值,但是df_ref在形状方面是不相关的和大小。

如何最好地为这种情况编写函数?

谢谢。

编辑:我当前的“解决方案”是使用lambda ...

f = lambda L, option : calc_fitted_values(L, option, df_ref)
df['outputval'] = np.vectorize(f)(df['L'].values, df['option'].values)

但这似乎很慢。可能是由于每次使用df_ref进行的计算,所以拥有一个返回lambda定义的函数的函数会更好吗?不确定最好的方法。

1 个答案:

答案 0 :(得分:0)

您可以使用partial

from functools import partial

func = partial(calc_fitted_values, df_ref=df_ref)

df['outputval'] = np.vectorize(func)(df['L'], df['option'])

我希望这会有所帮助