Pyspark 数据框获取列的所有值 [英] Pyspark dataframe get all values of a column
问题描述
我想获取 pyspark 数据框中一列的所有值.我进行了一些搜索,但从未找到有效且简短的解决方案.
I want to get all values of a column in pyspark dataframe. I did some search, but I never find a efficient and short solution.
假设我想在名为name"的列中获取一个值.我有一个解决方案:
Assuming I want to get a values in the column called "name". I have a solution:
sum(dataframe.select("name").toPandas().values.tolist(),[])
它有效,但效率不高,因为它转换为熊猫然后展平列表......有没有更好和更短的解决方案?
It works, but it is not efficient since it converts to pandas then flatten the list... Is there a better and short solution?
推荐答案
Below Options 将提供比 sum
更好的性能.
Below Options will give better performance than sum
.
使用collect_list
import pyspark.sql.functions as f
my_list = df.select(f.collect_list('name')).first()[0]
使用 RDD:
my_list = df.select("name").rdd.flatMap(lambda x: x).collect()
我不确定,但在我的几次压力测试中,collect_list
提供了更好的性能.如果有人可以确认,那就太好了.
I am not certain but in my couple of stress test, collect_list
gives better performance. Will be great if someone can confirm.
这篇关于Pyspark 数据框获取列的所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!