Pyspark Dataframe 从列中获取唯一元素,字符串作为元素列表 [英] Pyspark Dataframe get unique elements from column with string as list of elements

查看:61
本文介绍了Pyspark Dataframe 从列中获取唯一元素,字符串作为元素列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框(它是通过从 azure 中的多个 blob 加载创建的),其中有一列是 ID 列表.现在,我想要整个列中的唯一 ID 列表:

I have a dataframe (which is created by loading from multiple blobs in azure) where I have a column which is list of IDs. Now, I want a list of unique IDs from this entire column:

这是一个例子 -

df - 
| col1 | col2 | col3  |
| "a"  | "b"  |"[q,r]"|
| "c"  | "f"  |"[s,r]"|

这是我预期的回复:

resp = [q, r, s]

知道怎么去吗?

我目前的方法是将 col3 中的字符串转换为 python 列表,然后以某种方式将它们展平.

My current approach is to convert the strings in col3 to python lists and then maybe flaten them out somehow.

但到目前为止我还做不到.我尝试在 pyspark 中使用用户定义的函数,但它们只返回字符串而不是列表.

But so far I am not able to do so. I tried using user defined functions in pyspark but they only return strings and not lists.

FlatMaps 仅适用于 RDD,不适用于数据帧,因此它们不在图片中.

FlatMaps only work on RDD not on Dataframes so they are out of picture.

也许我可以在从 RDD 到数据帧的转换过程中指定这一点.但不确定如何做到这一点.

Maybe there is way where I can specify this during the conversion from RDD to dataframe. But not sure how to do that.

推荐答案

这里是一个只使用 DataFrame 函数的方法:

Here is a method using only DataFrame functions:

df = spark.createDataFrame([('a','b','[q,r,p]'),('c','f','[s,r]')],['col1','col2','col3'])

df=df.withColumn('col4', f.split(f.regexp_extract('col3', '\[(.*)\]',1), ','))

df.select(f.explode('col4').alias('exploded')).groupby('exploded').count().show()

这篇关于Pyspark Dataframe 从列中获取唯一元素,字符串作为元素列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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