首页 > 解决方案 > 如何在课堂上使用 Pandas UDF

问题描述

我试图弄清楚如何在 Python 的 Class 方法中使用selfinPandasUDF.GroupBy.Apply并在其中传递参数。我尝试了很多不同的方法,但无法使其发挥作用。我还在互联网上广泛搜索了一个 PandasUDF 的示例,该示例在带有 self 和 arguments 的类中使用,但找不到类似的东西。我知道如何用Pandas.GroupBy.Apply.

我可以使它工作的唯一方法是声明它为静态方法

class Train:
    return_type = StructType([
        StructField("div_nbr", FloatType()),
        StructField("store_nbr", FloatType()),
        StructField("model_str", BinaryType())
    ])
    function_type = PandasUDFType.GROUPED_MAP

    def __init__(self):
       ............

    def run_train(self):
         output = sp_df.groupby(['A', 'B']).apply(self.model_train)
         output.show(10)

    @staticmethod
    @pandas_udf(return_type, function_type)
    def model_train(pd_df):
        features_name = ['days_into_year', 'months_into_year', 'minutes_into_day', 'hour_of_day', 'recency']

        X = pd_df[features_name].copy()
        Y = pd.DataFrame(pd_df['trans_type_value']).copy()

        estimator_1 = XGBRegressor(max_depth=3, learning_rate=0.1, n_estimators=300, verbosity=1,
                                   objective='reg:squarederror', booster='gbtree', n_jobs=-1, gamma=0,
                                   min_child_weight=5, max_delta_step=0, subsample=0.6, colsample_bytree=0.8,
                                   colsample_bylevel=1, colsample_bynode=1, reg_alpha=0, reg_lambda=1,
                                   scale_pos_weight=1, base_score=0.5, random_state=1234, missing=None,
                                   importance_type='gain')
        estimator_1.fit(X, Y)
        df_to_return = pd_df[['div_nbr', 'store_nbr']].drop_duplicates().copy()
        df_to_return['model_str'] = pickle.dumps(estimator_1)

        return df_to_return

我想在现实中实现的是声明return_typefunction_type,然后features_name__init__()PandasUDF中使用它,在执行时也传递要在函数内部使用的参数PandasUDF.GroupBy.Apply

如果有人可以帮助我,我将不胜感激。我是 PySpark 的新手。

标签: pandaspyspark

解决方案


推荐阅读