首页 > 解决方案 > 如何在 pyspark 2.1.0 中选择另一个数据框中不存在的行?

问题描述

环境

语境

我有两个具有以下结构的数据框:

数据框1:

id | ... | distance

数据框2:

id | ... | distance | other calculated values

第二个数据帧是基于数据帧 1 的过滤器创建的。此过滤器从数据帧 1 中仅选择距离 <= 30.0。

请注意,dataframe1 将在多行中包含相同的 ID。

问题

我需要从数据框 1 中选择 ID 未出现在数据框 2 中的行。

目的是选择 ID 没有小于或等于 30.0 的距离的行。

测试解决方案

我试过leftanti加入,根据不是官方文档而是互联网上的消息来源(因为,嘿,他们为什么要解释它?):select all rows from df1 that are not present in df2

distinct_id_thirty = within_thirty_km \
    .select("id") \
    .distinct()
not_within_thirty_km = data_with_straight_distance.join(
        distinct_id_thirty,
        "id",
        "leftanti")

在哪里:

问题

以上返回距离低于 30 的数据。所以我假设我做错了什么:

编辑:

这是我期望的一个最小示例:

data = [
    ("1", 15),
    ("1", 35),
    ("2", 15),
    ("2", 30),
    ("3", 35)]

data = spark.createDataFrame(data, ['id', 'distance'])

data.show()

thirty = data.filter(col("distance") <= 30)

dist_thirty = thirty.select("id").distinct()

not_in_thirty = data.join(dist_thirty, "id", "left_anti")

print("thirty")
thirty.show()

print("distinst thirty")
dist_thirty.show()

print("not_in_thirty")
not_in_thirty.show()

输出:

+---+--------+
| id|distance|
+---+--------+
|  3|      35|
+---+--------+

但我确实在我的实际数据上运行距离 <= 30。

标签: pythondataframepysparkapache-spark-2.0

解决方案



推荐阅读