我有一個像火花資料框
key value
1111 {'fruit1': 'apple', 'fruit2': 'mango'}
2222 {'fruit1': 'orange'}
我想將 JSON(字串)轉換為新列
key fruit1 fruit2
1111 apple mango
2222 orange null
我不想手動指定來自 JSON 的鍵,因為有 100 多個鍵
uj5u.com熱心網友回復:
json_keys = df.selectExpr('explode(json_object_keys(value))').select(F.collect_set('col')).first()[0]
df.select('key', F.json_tuple('value', *json_keys).alias(*json_keys)).show()
---- ------ ------
| key|fruit1|fruit2|
---- ------ ------
|1111| apple| mango|
|2222|orange| null|
---- ------ ------
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/441150.html
標籤:Python 阿帕奇火花 pyspark apache-spark-sql
