过滤Spark SQL数据帧的距离

问题描述 投票:0回答:1

我有一个带有纬度和经度列的Spark SQL DataDrame,我试图通过计算到输入的距离来过滤低于阈值的行。我目前的代码看起来像。我使用geopygreat_circle)来计算lat长对之间的距离。

from geopy.distance import great_circle

point = (10, 20)
threshold = 10
filtered_df = df.filter(great_circle(point, (df.lat, df.lon)) < threshold)

当我运行此代码时,我收到以下错误

ValueError: Cannot convert column into bool: please use '&' for 'and', '|' for 'or', '~' for 'not' when building DataFrame boolean expressions. 

我很困惑过滤器表达式的哪一部分是错误的。

python apache-spark pyspark apache-spark-sql geopy
1个回答
2
投票

你不能在DataFrame上应用普通的Python函数。你必须使用udf

from pyspark.sql.functions import udf

@udf("float")
def great_circle_udf(x, y):
    return great_circle(x, y).kilometers

并将其应用于列

from pyspark.sql.functions import lit, struct

point = struct(lit(10), lit(20))
df.filter(great_circle_udf(point, struct(df.lat, df.lon)) < threshold))

装饰器语法将从2.2开始工作,对于早期版本,您需要标准的udf调用:

udf(great_circle, FloatType())
© www.soinside.com 2019 - 2024. All rights reserved.