我试图找出数据框中单行不同列scala最大值。
数据框中可用的数据如下。
+-------+---------------------------------------+---------------------------------------+---------------------------------------+
| NUM| SIG1| SIG2| SIG3|
+-------+---------------------------------------+---------------------------------------+---------------------------------------+
|XXXXX01|[{"TIME":1569560531000,"VALUE":3.7825}]|[{"TIME":1569560531001,"VALUE":4.7825}]|[{"TIME":1569560531002,"VALUE":2.7825}]|
|XXXXX01|[{"TIME":1569560541001,"VALUE":1.7825}]|[{"TIME":1569560541000,"VALUE":8.7825}]|[{"TIME":1569560541003,"VALUE":5.7825}]|
|XXXXX01|[{"TIME":1569560531000,"VALUE":3.7825}]|[{"TIME":1569560531009,"VALUE":3.7825}]| null |
|XXXXX02|[{"TIME":1569560531000,"VALUE":5.7825}]|[{"TIME":1569560531007,"VALUE":8.7825}]|[{"TIME":1569560531006,"VALUE":3.7825}]|
|XXXXX02|[{"TIME":1569560531000,"VALUE":9.7825}]|[{"TIME":1569560531009,"VALUE":1.7825}]|[{"TIME":1569560531010,"VALUE":3.7825}]|
并且模式是
scala> DF.printSchema
root
|-- NUM: string (nullable = true)
|-- SIG1: string (nullable = true)
|-- SIG2: string (nullable = true)
|-- SIG3: string (nullable = true)
预期输出如下。
+-------+--------------+----------+------------+------------+
| NUM| TIME | SIG1| | SIG2 | SIG3 |
+-------+--------------+----------+------------+------------+
|XXXXX01| 1569560531002| 3.7825 | 4.7825 | 2.7825 |
|XXXXX01| 1569560541003| 1.7825 | 8.7825 | 5.7825 |
|XXXXX01| 1569560531009| 3.7825 | 3.7825 | null |
|XXXXX02| 1569560531007| 5.7825 | 8.7825 | 3.7825 |
|XXXXX02| 1569560531010| 9.7825 | 1.7825 | 3.7825 |
我需要从单行中添加一个具有最高时间的新列,并仅使用它们的值SIG列。
基本上,每列中的TIME将被该行中可用的最高TIME值替换,并爆炸TIME和VALUE。
是否有任何UDF/功能来实现这一点?提前感谢。
使用get_json_object
函数从存储为字符串的json中提取值。
那就很简单了:
DF.withColumn("TIME", greatest(get_json_object('SIG1, "$[0].TIME"),
get_json_object('SIG2, "$[0].TIME"),
get_json_object('SIG3, "$[0].TIME")))
.withColumn("SIG1", get_json_object('SIG1, "$[0].VALUE"))
.withColumn("SIG2", get_json_object('SIG2, "$[0].VALUE"))
.withColumn("SIG3", get_json_object('SIG3, "$[0].VALUE"))
.show