【发布时间】:2019-06-01 18:38:17
【问题描述】:
我是 Pyspark 的新手,我正在研究如何将列类型转换为 dict 类型,然后使用 explode 将该列展平为多个列。
这是我的数据框的样子:
col1 | col2 |
-----------------------
test:1 | {"test1":[{"Id":"17","cName":"c1"},{"Id":"01","cName":"c2","pScore":0.003609}],
{"test8":[{"Id":"1","cName":"c11","pScore":0.0},{"Id":"012","cName":"c2","pScore":0.003609}]
test:2 | {"test1:subtest2":[{"Id":"18","cName":"c13","pScore":0.00203}]}
现在,这个数据框的架构是
root
|-- col1: string (nullable = true)
|-- col2: string (nullable = true)
我想要的输出是这样的:
col1 | col2 | Id | cName | pScore |
------------------------------------------------
test:1 | test1 | 17 | c1 | null |
test:1 | test1 | 01 | c2 | 0.003609|
test:1 | test8 | 1 | c11 | 0.0 |
test:1 | test8 | 012| c2 | 0.003609|
test:2 | test1:subtest2 | 18 | c13 | 0.00203 |
我无法为 col2 定义正确的架构以将其类型从 String 转换为 json 或 dict。然后,我希望能够将值分解为多列,如上所示。任何帮助将不胜感激。我正在使用 Spark 2.0 +。
谢谢!
【问题讨论】:
-
你知道col2中JSON的结构是什么吗?会不会总是像
{'unique_key': [{"Id": "XX", "cName": "XX", "pScore": X.XX}, ...]}? -
@RichardNemeth:是的,事情总是这样。
标签: python apache-spark pyspark apache-spark-sql explode