简体   繁体   English

udf(用户定义函数)如何在 pyspark 中工作?

[英]How does udf (user defined function) work in pyspark?

I want to understand the working of udf in pyspark.我想了解 udf 在 pyspark 中的工作原理。 Does a python shell opens up everytime we use a udf on top of a dataframe?每次我们在数据帧上使用 udf 时,python shell 是否会打开?

UDF can be given to PySpark in 2 ways. UDF 可以通过两种方式提供给 PySpark。

  1. UDF can be defined in Scala and run using PySpark UDF 可以在 Scala 中定义并使用 PySpark 运行
  2. UDF can be defined in Python and run by PySpark UDF 可以在 Python 中定义并由 PySpark 运行

In first case UDF will run as part of Executor JVM itself, since UDF itself is defined in Scala.在第一种情况下,UDF 将作为 Executor JVM 本身的一部分运行,因为 UDF 本身是在 Scala 中定义的。 There is no need to create python process.无需创建python进程。

In second case for each executor a python process will be started.在第二种情况下,每个执行程序都会启动一个 python 进程。 data will be serialised and deserialised between executor and python to process.数据将在 executor 和 python 之间序列化和反序列化以进行处理。 This leads to lots of performance impact and overhead on spark job.这会导致大量的性能影响和火花作业的开销。

usually it is preferred to use Scala based UDF, since they will give you better performance.通常首选使用基于 Scala 的 UDF,因为它们会给你更好的性能。

in spark 2.x There is something called Pandas Udf(vectorised UDF).在 spark 2.x 中有一种叫做 Pandas Udf(矢量化 UDF)的东西。 They are implemented using Pandas(Converting Dataframe using apache arrow).它们是使用 Pandas 实现的(使用 apache 箭头转换数据帧)。 Basically you write code in python but that code is converted and run using pandas.基本上你用python编写代码,但该代码被转换并使用pandas运行。 which drastically improves performance of UDF in python.这极大地提高了 Python 中 UDF 的性能。 I hope this helps.我希望这有帮助。

Spark runs a python process parallel to each executor and passes data back and forth between the Scala part (the executor) and python. Spark 与每个执行器并行运行一个 Python 进程,并在 Scala 部分(执行器)和 Python 之间来回传递数据。

This has a lot of implications for performance and memory consumption (and management of them when you tune a spark job)这对性能和内存消耗(以及在调整 Spark 作业时管理它们)有很多影响

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM