我正在讀取一個包含以下結構的 .json 檔案,我需要以列形式生成一個包含此資料的 csv,我知道我不能直接在 csv 中寫入陣列型別的物件,我使用了 explode洗掉我需要的欄位的函式,能夠將它們保留為柱狀形式,但是在 csv 中寫入資料框時,使用explode函式時出現錯誤,據我了解這是不可能的同一個選擇中的兩個變數,有人可以幫我做點別的嗎?
from pyspark.sql.functions import col, explode
from pyspark.sql import SparkSession
spark = (SparkSession.builder
.master("local[1]")
.appName("sample")
.getOrCreate())
df = (spark.read.option("multiline", "true")
.json("data/origin/crops.json"))
df2 = (explode('history').alias('history'), explode('trial').alias('trial'))
.select('history.started_at', 'history.finished_at', col('id'), trial.is_trial, trial.ws10_max))
(df2.write.format('com.databricks.spark.csv')
.mode('overwrite')
.option("header","true")
.save('data/output/'))
root
|-- history: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- finished_at: string (nullable = true)
| | |-- started_at: string (nullable = true)
|-- id: long (nullable = true)
|-- trial: struct (nullable = true)
| |-- is_trial: boolean (nullable = true)
| |-- ws10_max: double (nullable = true)
我正在嘗試回傳這樣的東西
| 開始時間 | 完成時間 | is_trial | ws10_max |
|---|---|---|---|
| 第一的 | 排 | 排 | |
| 第二 | 排 | 排 |
謝謝!
uj5u.com熱心網友回復:
在陣列上使用explode ,在結構上使用select("struct.*")。
df.select("trial", "id", explode('history').alias('history')),
.select('id', 'history.*', 'trial.*'))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/474816.html
