PySpark DataFrame:自定义爆炸函数 [英] PySpark DataFrame: Custom Explode Function

查看:71
本文介绍了PySpark DataFrame:自定义爆炸函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 udfs 实现自定义爆炸功能,以便我们可以获得有关项目的额外信息?例如,除了项目,我还想拥有项目的索引.

How to implement a custom explode function using udfs, so we can have extra information on items? For example, along with items, I want to have items' indices.

我不知道该怎么做的部分是当 udf 返回多个值时,我们应该将这些值作为单独的行放置.

The part I do not know how to do is when a udf returns multiple values and we should place those values as separate rows.

推荐答案

如果你需要自定义的explode函数,那么你需要写UDF来获取数组并返回数组.例如对于这个 DF:

If you need custom explode function, then you need to write UDF that gets array and returns array. For example for this DF:

df = spark.createDataFrame([(['a', 'b', 'c'], ), (['d', 'e'],)], ['array'])
df.show()
+---------+
|    array|
+---------+
|[a, b, c]|
|   [d, e]|
+---------+

添加索引和爆炸结果的函数可以是这样的:

The function that adds index and explodes the results can look like this:

from pyspark.sql.types import *
value_with_index = StructType([
    StructField('index', IntegerType()),
    StructField('letter', StringType())
])
add_indices = udf(lambda arr: list(zip(range(len(arr)), arr)), ArrayType(value_with_index))
df.select(explode(add_indices('array'))).select('col.index', 'col.letter').show()
+-----+------+
|index|letter|
+-----+------+
|    0|     a|
|    1|     b|
|    2|     c|
|    0|     d|
|    1|     e|
+-----+------+

这篇关于PySpark DataFrame:自定义爆炸函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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