相关文章推荐
帅气的领带  ·  【Pyspark ...·  2 周前    · 
高大的柿子  ·  mapstruct ...·  1 年前    · 
闷骚的跑步鞋  ·  oracle ...·  1 年前    · 

在 agg 中使用 pyspark groupBy 和一个自定义函数

0 人关注

我想用自定义agg函数对我的spark df进行groupBy。

def gini(list_of_values):
    sth is processing here
    return number output

我想得到这样的结果。

df.groupby('activity')['mean_event_duration_in_hours].agg(gini)

能否请您帮助我解决这个问题?

python
pandas
apache-spark
pyspark
Sebastian Kowalczykiewicz
Sebastian Kowalczykiewicz
发布于 2022-01-20
1 个回答
Jan Jaap Meijerink
Jan Jaap Meijerink
发布于 2022-01-20
0 人赞同

你可以创建一个 udf 像这样。

import pyspark.sql.functions as F
from pyspark.sql.types import FloatType
def gini(list_of_values):
    # sth is processing here
    return number_output
udf_gini = F.udf(gini, FloatType())
df.groupby('activity')\
    .agg(F.collect_list("mean_event_duration_in_hours").alias("event_duration_list"))\
    .withColumn("gini", udf_gini(F.col("event_duration_list")))

或者像这样把gini定义为一个UDF。

@udf(returnType=FloatType())
def gini(list_of_values):
    # sth is processing here
    return number_output