在pysparkDataframe中添加新列

fruv7luv  于 2021-07-14  发布在  Spark
关注(0)|答案(1)|浏览(304)

我正在尝试向我的pysaprkDataframe添加一个新的记录时区

from timezonefinder import TimezoneFinder
tf = TimezoneFinder()
df = df.withColumn("longitude",col("longitude").cast("float"))
df = df.withColumn("Latitude",col("Latitude").cast("float"))
df = df.withColumn("timezone",tf.timezone_at(lng=col("longitude"), lat=col("Latitude")))

我的错误率正在下降。

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

timezonefinder库用于通过传递地理坐标来查找时区。

Latitude, longitude = 20.5061, 50.358
tf.timezone_at(lng=longitude, lat=Latitude)
 -- 'Asia/Riyadh'
dzhpxtsq

dzhpxtsq1#

需要使用udf将列传递给python函数:

import pyspark.sql.functions as F

@F.udf('string')
def tfUDF(lng, lat):
    from timezonefinder import TimezoneFinder
    tf = TimezoneFinder()
    return tf.timezone_at(lng=lng, lat=lat)

df = df.withColumn("longitude", F.col("longitude").cast("float"))
df = df.withColumn("Latitude", F.col("Latitude").cast("float"))
df = df.withColumn("timezone", tfUDF(F.col("longitude"), F.col("Latitude")))

df.show()
+--------+---------+-----------+
|Latitude|longitude|   timezone|
+--------+---------+-----------+
| 20.5061|   50.358|Asia/Riyadh|
+--------+---------+-----------+

相关问题