这里有一个 PySpark 中的常见任务:如何在一个数据帧列中筛选另一个数据帧的唯一值?
方法 1
假设我们有两个数据帧 df1 和 df2,我们想要通过名为“id”的列来筛选 df1,其值需要来自 df2 中的“id”列。如果 df2 的“id”列的唯一值不太大,我们可以这样做:
python
Copy code
from pyspark.sql.functions import col
# Create the first DataFrame
df1 = spark.createDataFrame([(1, "a"), (2, "b"), (3, "c"), (4, "d")], ["id", "value"])
# Create the second DataFrame
df2 = spark.createDataFrame([(1, "x"), (2, "y")], ["id", "other_value"])
# Get the unique values of the second DataFrame's column
unique_values = df2.select("id").distinct().rdd.flatMap(lambda x: x).collect()
# Filter the first DataFrame's column based on the unique values
filtered_df1 = df1.filter(col("id").isin(unique_values))
在上面的示例中,filtered_df1 将只包含 df1 中 id 列在 df2 id 列中唯一值列表中的行。
方法 2
然而,上面使用 collect 的示例对于大型数据量可能不是最优的。在示例中,使用 .collect() 方法收集了第二个数据帧的唯一值。这是必要的,因为用于筛选第一个数据帧列的 .isin() 函数需要可迭代的值(例如列表,集合或元组)来检查。
但值得提醒的是,如果第二个 DataFrame 非常大并且

本文介绍在PySpark中如何基于一个数据帧的唯一值筛选另一个数据帧的方法,包括直接筛选与使用join操作,同时提供了重命名列及深度复制数据帧的技巧。
最低0.47元/天 解锁文章
888

被折叠的 条评论
为什么被折叠?



