【发布时间】:2021-02-12 15:51:15
【问题描述】:
我想创建一个新列,它是其他一些列的 JSON 表示。列表中的键、值对。
来源:
| origin | destination | count |
|---|---|---|
| toronto | ottawa | 5 |
| montreal | vancouver | 10 |
我想要什么:
| origin | destination | count | json |
|---|---|---|---|
| toronto | ottawa | 5 | [{"origin":"toronto"},{"destination","ottawa"}, {"count": "5"}] |
| montreal | vancouver | 10 | [{"origin":"montreal"},{"destination","vancouver"}, {"count": "10"}] |
(一切都可以是字符串,没关系)。
我尝试过类似的方法:
df.withColumn('json', to_json(struct(col('origin'), col('destination'), col('count'))))
但它会在一个对象中创建包含所有 key:value 对的列:
{"origin":"United States","destination":"Romania"}
如果没有 UDF,这可能吗?
【问题讨论】:
标签: apache-spark pyspark apache-spark-sql key-value