【发布时间】:2020-08-28 19:07:48
【问题描述】:
我从 Pyspark 网站获取了以下 UDF,因为我试图了解是否有性能改进。我做了很大范围的数字,但都花费了几乎相同的时间,我做错了什么?
谢谢!
import pandas as pd
from pyspark.sql.functions import col, udf
from pyspark.sql.types import LongType
import time
start = time.time()
# Declare the function and create the UDF
def multiply_func(a, b):
return a * b
multiply = udf(multiply_func, returnType=LongType())
# The function for a pandas_udf should be able to execute with local Pandas data
x = pd.Series(list(range(1, 1000000)))
print(multiply_func(x, x))
# 0 1
# 1 4
# 2 9
# dtype: int64
end = time.time()
print(end-start)
这里是 Pandas UDF
import pandas as pd
from pyspark.sql.functions import col, pandas_udf
from pyspark.sql.types import LongType
import time
start = time.time()
# Declare the function and create the UDF
def multiply_func(a, b):
return a * b
multiply = pandas_udf(multiply_func, returnType=LongType())
# The function for a pandas_udf should be able to execute with local Pandas data
x = pd.Series(list(range(1, 1000000)))
print(multiply_func(x, x))
# 0 1
# 1 4
# 2 9
# dtype: int64
【问题讨论】:
-
pandas_udf 针对分组操作进行了优化并且速度更快,例如在 groupBy 之后应用 pandas_udf。分组允许 pandas 执行矢量化操作,并且会比普通的 udf 更快。对于像 a*b 这样的正常情况,正常的 spark udf 就足够了,而且速度更快。
标签: apache-spark pyspark