使用when/otherwise时出现pyspark语法错误

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

我有一个具有以下架构的数据框:

   root
   |-- key: string (nullable = true)
   |-- points: array (nullable = true)
   |    |-- element: struct (containsNull = true)
   |    |    |-- time: long (nullable = true)
   |    |    |-- latitude: double (nullable = true)
   |    |    |-- longitude: double (nullable = true)
   |    |    |-- altitude: float (nullable = true)

我添加一个 altitude_list 列,它是高度字段的字符串串联

df.withColumn("altitude_list", stringify_altitudes("points")).drop("points").show()

我正在使用这个函数来字符串化

def stringify_litetrack_points(points):
   return F.expr("array_join(transform(points, x -> concat(round(x.altitude))), ':')")

这个作品找到了。但是,有时海拔高度为 None (空),在这些情况下,该函数对该点数组条目不执行任何操作,这意味着如果我有五个点并且其中一个点具有 None 海拔高度,则生成的海拔高度列表将只有四个项目。我要为 None 值插入一个文字。

如果尝试使用when().otherwise()如下...

def stringify_litetrack_points(points):
    return F.expr("array_join(transform(points, x -> concat(when(x.altitude.isNotNull(), round(x.altitude)).otherwise('*'))), ':')")

...但是我在 else() 处遇到语法错误。

ParseException: 
Syntax error at or near '('(line 1, pos 98)

== SQL ==
array_join(transform(points, x -> concat(when(x.altitude.isNotNull(), round(x.altitude)).otherwise('*'))), ':')
--------------------------------------------------------------------------------------------------^^^

我做错了什么?我应该以不同的方式做这件事吗?谢谢。

dataframe pyspark
1个回答
0
投票

不要使用 case when... 使用(更简单的)ifnull:

F.expr("array_join(transform(points, x -> ifnull(round(x.altitude), '*')),':')"

内部

concat
不是必需的,
array_join
已经完成了工作。

© www.soinside.com 2019 - 2024. All rights reserved.