pyspark-对Array(Integer())类型的列中的值求和的最佳方法 [英] pyspark -- best way to sum values in column of type Array(Integer())

查看:201
本文介绍了pyspark-对Array(Integer())类型的列中的值求和的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说这是我的数据框...

Lets say this is my dataframe ...

name | scores
Dan  |  [10,5,2,12]
Ann  |  [ 12,3,5]
Jon  |  [ ] 

所需的输出类似

name | scores         | Total
Dan  |  [10,5,2,12]   | 29
Ann  |   [ 12,3,5]    | 20
Jon  |  [ ]           | 0

我沿着....的方向制作了UDF.

I made a UDF along the lines of ....

sum_cols = udf(lambda arr: if arr == [] then 0 else __builtins__.sum(arr),IntegerType())

df.withColumn('Total', sum_cols(col('scores'))).show()

但是,我了解到,UDF在使用纯pySpark函数方面相对较慢.

However, I have learned that UDFs are relatively slow to pure pySpark functions.

在没有UDF的情况下在pySpark中执行上述代码的任何方法吗?

Any way to do code above in pySpark without a UDF ?

推荐答案

您可以使用更高阶的SQL函数 AGGREGATE (从函数式编程中减少),如下所示:

You can use a higher-order SQL function AGGREGATE (reduce from functional programming), like this:

import pyspark.sql.functions as F
df = df.select(
  'name',
  F.expr('AGGREGATE(scores, 0, (acc, x) -> acc + x)').alias('Total')
)

第一个参数是数组列,第二个参数是初始值(应与您求和的值具有相同的类型,因此,如果输入不是整数,则可能需要使用"0.0"或"DOUBLE(0)"等)第三个参数是lambda函数,它将数组的每个元素添加到一个累加器变量(在开始时,它将被设置为初始值0).

First argument is the array column, second is initial value (should be of same type as the values you sum, so you may need to use "0.0" or "DOUBLE(0)" etc if your inputs are not integers) and third argument is a lambda function, which adds each element of the array to an accumulator variable (in the beginning this will be set to the initial value 0).

转换将在单个投影运算符中运行,因此将非常有效.另外,您不必事先知道数组的大小,并且数组的每一行长度可以不同.

The transformation will run in a single projection operator, thus will be very efficient. Also you do not need to know the size of the arrays in advance and the array can have different length on each row.

这篇关于pyspark-对Array(Integer())类型的列中的值求和的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆