[英]How to convert a Spark Dataframe column from vector to a set?
I need to process a dataset to identify frequent itemsets.我需要处理一个数据集来识别频繁项集。 So the input column must be a vector.
所以输入列必须是一个向量。 The original column is a string with the items separated by comma, so i did the following:
原始列是一个字符串,项目以逗号分隔,因此我执行了以下操作:
functions.split(out_1['skills'], ',')
The problem is the, for some rows, I have duplicated values in the skills
and this is causing an error when trying to identify the frequent itemsets.问题是,对于某些行,我在
skills
有重复的值,这在尝试识别频繁项集时导致错误。
I wanted to convert the vector to a set to remove the duplicated elements.我想将向量转换为集合以删除重复的元素。 Something like this:
像这样的东西:
functions.to_set(functions.split(out_1['skills'], ','))
But I could not find a function to convert a column from vector to set, ie, there is no to_set
function.但是我找不到将列从向量转换为集合的函数,即没有
to_set
函数。
How can I accomplish what I want, ie, remove the duplicated elements from the vector?我怎样才能完成我想要的,即从向量中删除重复的元素?
You can convert the set
function in python to a udf using functions.udf(set)
and then apply it to the array column: 您可以使用
functions.udf(set)
将python中的set
函数转换为udf,然后将其应用于array列:
df.show()
+-------+
| skills|
+-------+
|a,a,b,c|
| a,b,c|
|c,d,e,e|
+-------+
import pyspark.sql.functions as F
df.withColumn("unique_skills", F.udf(set)(F.split(df.skills, ","))).show()
+-------+-------------+
| skills|unique_skills|
+-------+-------------+
|a,a,b,c| [a, b, c]|
| a,b,c| [a, b, c]|
|c,d,e,e| [c, d, e]|
+-------+-------------+
It is recommended, when possible, to use native spark functions instead of UDFs for efficiency reasons.出于效率原因,建议在可能的情况下使用本机 spark 函数而不是 UDF。 There is a dedicated function to leave only unique items in an array column:
array_distinct()
introduced in spark 2.4.0有一个专用函数可以在数组列中只保留唯一项: spark 2.4.0 中引入的
array_distinct()
from pyspark import Row
from pyspark.shell import spark
import pyspark.sql.functions as F
df = spark.createDataFrame([
Row(skills='a,a,b,c'),
Row(skills='a,b,c'),
Row(skills='c,d,e,e'),
])
df = df.withColumn('skills_arr', F.array_distinct(F.split(df.skills, ",")))
result:结果:
+-------+----------+
|skills |skills_arr|
+-------+----------+
|a,a,b,c|[a, b, c] |
|a,b,c |[a, b, c] |
|c,d,e,e|[c, d, e] |
+-------+----------+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.