您好,我遇到了一个问题,我的行中有两列单词数组。
column1, column2
["a", "b" ,"b", "c"], ["a","b", "x", "y"]
基本上我想计算列之间每个单词的出现次数以得到两个数组:
[1, 2, 1, 0, 0],
[1, 1, 0, 1, 1]
因此,“a”在每个数组中出现一次,“b”在第 1 列中出现两次,在第 2 列中出现一次,“c”仅在第 1 列中出现,“x”和“y”仅在第 2 列中出现。依此类推。
我尝试查看 ml 库中的 CountVectorizer 函数,但不确定它是否按行工作,每列中的数组可能非常大?并且 0 值(其中一个单词出现在一列中,但不在另一列中出现)似乎没有得到贯彻。
感谢任何帮助。
最佳答案
对于 Spark 2.4+,您可以使用 DataFrame API 和内置数组函数来实现这一点。
首先,使用 array_union
获取每行的所有单词功能。然后,使用transform
函数来转换单词数组,其中每个元素使用 size
计算每列中出现的次数和 array_remove
功能:
df = spark.createDataFrame([(["a", "b", "b", "c"], ["a", "b", "x", "y"])], ["column1", "column2"])
df.withColumn("words", array_union("column1", "column2")) \
.withColumn("occ_column1",
expr("transform(words, x -> size(column1) - size(array_remove(column1, x)))")) \
.withColumn("occ_column2",
expr("transform(words, x -> size(column2) - size(array_remove(column2, x)))")) \
.drop("words") \
.show(truncate=False)
输出:
+------------+------------+---------------+---------------+
|column1 |column2 |occ_column1 |occ_column2 |
+------------+------------+---------------+---------------+
|[a, b, b, c]|[a, b, x, y]|[1, 2, 1, 0, 0]|[1, 1, 0, 1, 1]|
+------------+------------+---------------+---------------+
关于machine-learning - 单行上的字符串索引器、CountVectorizer Pyspark,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60119554/