python - 如何在 pyspark 2.1.0 中选择另一个数据框中不存在的行?
问题描述
环境
- 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")
在哪里:
within_thrity_km
是过滤器结果的数据filter(col("distance") <= 30.0)
帧data_with_straight_distance
data_with_straight_distance
是一个包含所有数据的数据框。distinct_id_thirty
是一个数据框,其中包含与数据框不同的 ID 列表within_thirty_km
问题
以上返回距离低于 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。
解决方案
"leftanti"
应按照"left_anti"
以下文档替换:
https ://spark.apache.org/docs/2.4.0/api/python/pyspark.sql.html#pyspark.sql.DataFrame.join
推荐阅读
- html - Django Project - 来自 json 文件的帖子未在浏览器中呈现
- javascript - Plotly.js:为什么在更新绘图时必须使用嵌套数组?
- electron - 您是否需要访问目标操作系统才能对电子应用程序进行代码签名
- angular - 数组推入角度后视图页面不刷新
- django - How to make ChoiceField not required?
- c++ - 使用 Mongo C++ 驱动程序编辑 BSON 文档的字段值
- angular - 登录后重定向到页面并返回页面
- javascript - 未模拟的方法的开玩笑测试调用
- c# - Invoke Method, pass object as type
- javascript - Transforming LDAP group memberships to SAML Attributes in Keycloak