pandas - 如何在课堂上使用 Pandas UDF
问题描述
我试图弄清楚如何在 Python 的 Class 方法中使用self
inPandasUDF.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_type
和function_type
,然后features_name
在__init__()
PandasUDF中使用它,在执行时也传递要在函数内部使用的参数PandasUDF.GroupBy.Apply
如果有人可以帮助我,我将不胜感激。我是 PySpark 的新手。
解决方案
推荐阅读
- gps - 使用 GNSS SDR sim 演示欺骗
- swift - Core Data 抽象实体超级初始化器
- javascript - 试图从后端发送一个 zip 到前端
- c++ - cmake 类似于 qmake 字符串文字
- sql - SQL:根据时间戳和聊天伙伴分组消息
- sharepoint-online - MSAL AD 令牌对 SharePoint Online CSOM 无效
- reactjs - eslint 插件 fp、jest 和 react 测试库导致不必要的 linting 错误
- php - 验证公式未保存为函数
- node.js - 函数附加类型号
- c# - 将布局表单发送到其他页面时出现问题?