您好,数据工程师!
我正在尝试使用名为Astral的类中的方法编写pyspark udf
这是udf:
def time_from_solar_noon(d, y):
noon = astral.Astral().solar_noon_utc
time = noon(d, y)
return time
solarNoon = F.udf(lambda d, y: time_from_solar_noon(d,y), TimestampType())
按照我现在的理解,该类将针对我的数据框中的每行实例化,这将导致工作非常缓慢。
如果我从函数中删除类实例:
noon = astral.Astral().solar_noon_utc
def time_from_solar_noon(d, y):
time = noon(d, y)
return time
我收到以下错误消息:
[Previous line repeated 326 more times]
RecursionError: maximum recursion depth exceeded while calling a Python object
所以这是我的问题,我认为应该有可能通过执行者/线程至少有一个类实例化,而不是在数据框中逐行进行实例化,我该怎么做?
感谢帮助
答案 0 :(得分:0)
就像数据库连接一样,您可以使用mapPartitions
来实例化有限数量的此类实例:
In [1]: from datetime import date
...: from astral import Astral
...:
...: df = spark.createDataFrame(
...: ((date(2019, 10, 4), 0),
...: (date(2019, 10, 4), 19)),
...: schema=("date", "longitude"))
...:
...:
...: def solar_noon(rows):
...: a = Astral() # initialize the class once per partition
...: return ((a.solar_noon_utc(date=r.date, longitude=r.longitude), *r)
...: for r in rows) # reuses the same Astral instance for all rows in this partition
...:
...:
...: (df.rdd
...: .mapPartitions(solar_noon)
...: .toDF(schema=("solar_noon_utc", *df.columns))
...: .show()
...: )
...:
...:
+-------------------+----------+---------+
| solar_noon_utc| date|longitude|
+-------------------+----------+---------+
|2019-10-04 13:48:58|2019-10-04| 0|
|2019-10-04 12:32:58|2019-10-04| 19|
+-------------------+----------+---------+
这是相当有效的,因为将函数(solar_noon
分配给了每个工作程序,并且每个分区只能容纳一次该类,而该分区可以容纳很多行。