新 Dataframe 列作为其他行的通用函数 (spark)

New Dataframe column as a generic function of other rows (spark)

如何有效地在DataFrame中创建一个新列,它是[=]中其他行的函数13=]?

这是我描述的问题的 spark 实现 :

from nltk.metrics.distance import edit_distance as edit_dist
from pyspark.sql.functions import col, udf
from pyspark.sql.types import IntegerType

d = {
    'id': [1, 2, 3, 4, 5, 6],
    'word': ['cat', 'hat', 'hag', 'hog', 'dog', 'elephant']
}

spark_df = sqlCtx.createDataFrame(pd.DataFrame(d))
words_list = list(spark_df.select('word').collect())

get_n_similar = udf(
    lambda word: len(
        [
            w for w in words_list if (w['word'] != word) and 
            (edit_dist(w['word'], word) < 2)
        ]
    ),
    IntegerType()
)

spark_df.withColumn('n_similar', get_n_similar(col('word'))).show()

输出:

+---+--------+---------+
|id |word    |n_similar|
+---+--------+---------+
|1  |cat     |1        |
|2  |hat     |2        |
|3  |hag     |2        |
|4  |hog     |2        |
|5  |dog     |1        |
|6  |elephant|0        |
+---+--------+---------+

这里的问题是我不知道如何告诉 spark 将当前行与 Dataframe 中的其他行进行比较,而无需先将值收集到 [=17] =].有没有办法在不调用 collect 的情况下应用其他行的通用函数?

The problem here is that I don't know a way to tell spark to compare the current row to the other rows in the Dataframe without first collecting the values into a list.

UDF 在这里不是一个选项(你不能在 udf 中引用分布式 DataFrame)直接翻译你的逻辑是笛卡尔积和聚合:

from pyspark.sql.functions import levenshtein, col

result = (spark_df.alias("l")
    .crossJoin(spark_df.alias("r"))
    .where(levenshtein("l.word", "r.word") < 2)
    .where(col("l.word") != col("r.word"))
    .groupBy("l.id", "l.word")
    .count())

但实际上你应该尝试做一些更有效率的事情:Efficient string matching in Apache Spark

根据问题的不同,您应该尝试找到其他近似值以避免完整的笛卡尔积。

如果您想保留没有匹配项的数据,您可以跳过一个过滤器:

(spark_df.alias("l")
    .crossJoin(spark_df.alias("r"))
    .where(levenshtein("l.word", "r.word") < 2)
    .groupBy("l.id", "l.word")
    .count()
    .withColumn("count", col("count") - 1))

或(更慢,但更通用),通过引用返回:

(spark_df
    .select("id", "word")
    .distinct()
    .join(result, ["id", "word"], "left")
    .na.fill(0))