我有數據框,它是左連接的產物?,F在我想創建 json 結構。我嘗試使用不同的選項,但無法創建它。這是我的數據框:col1 col2 col3 col41111 name aaa bbb1111 name ccc ddd1111 name iii kkk1112 name1 abcd def1112 name1 DEFG ABXC所需的 json 結構是:{col1: 1111, col2: name, details: [{col3: aaa, col4: bbb}, {col3: ccc, col4: ddd}, {col3: iii, col4: kkk}]},{col1: 1112, col2: name1, details: [{col3: abcd, col4: def}, {col3: DEFG, col4: ABXC}]}Python
1 回答

慕斯709654
TA貢獻1840條經驗 獲得超5個贊
你可以這樣做:
import pyspark.sql.functions as f
df = df.withColumn("details", f.to_json(f.struct("col3", "col4")))
df = df.groupBy(*["col1", "col2"]).agg(f.collect_list("details").alias("details"))
df.write.format('json').save('/path/file_name.json')
添加回答
舉報
0/150
提交
取消