我无法理解functools中的部分工作原理.我从这里得到以下代码:
>>> sum = lambda x, y : x + y
>>> sum(1, 2)
3
>>> incr = lambda y : sum(1, y)
>>> incr(2)
3
>>> def sum2(x, y):
return x + y
>>> incr2 = functools.partial(sum2, 1)
>>> incr2(4)
5
Run Code Online (Sandbox Code Playgroud)
现在就行了
incr = lambda y : sum(1, y)
Run Code Online (Sandbox Code Playgroud)
我得到的是,无论我传递给incr它的任何论点都将被传递y给lambda哪个将返回sum(1, y)ie 1 + y.
我明白那个.但我不明白这一点incr2(4).
如何在部分函数中4传递x?对我来说,4应该更换sum2.x和之间有什么关系 …
我试图弄清楚如何在 Python 中的类方法中使用selfinPandasUDF.GroupBy.Apply并在其中传递参数。我尝试了很多不同的方法但无法使其发挥作用。我还在互联网上广泛搜索了 PandasUDF 的示例,该示例在带有 self 和参数的类中使用,但找不到类似的内容。我知道如何用 来做所有前面提到的事情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, …Run Code Online (Sandbox Code Playgroud) 我正在尝试应用带有两个参数的 pandas_udf。但我有这个错误。首先我尝试使用一个参数,没问题:
from pyspark.sql.functions import pandas_udf, PandasUDFType
from pyspark.sql import SparkSession
from pyspark.sql.types import *
spark = SparkSession \
.builder \
.config('spark.cores.max', 100) \
.getOrCreate()
df = spark.createDataFrame(
[(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],
("id", "v"))
Run Code Online (Sandbox Code Playgroud)
数据是这样的
+---+----+
| id| v|
+---+----+
| 1| 1.0|
| 1| 2.0|
| 2| 3.0|
| 2| 5.0|
| 2|10.0|
+---+----+
Run Code Online (Sandbox Code Playgroud)
我的 pandas_udf 函数是
@pandas_udf("double", PandasUDFType.GROUPED_AGG)
def count_udf(v):
cond = v<=3
res = v[cond].count()
return res
df.groupby("id").agg(count_udf(df['v'])).show()
Run Code Online (Sandbox Code Playgroud)
结果是
+---+------------+
| …Run Code Online (Sandbox Code Playgroud)