我目前正在從事一項作業,將嵌套的 Json 檔案加載為資料幀,對其執行一些轉換,然后將其加載到增量表中。我使用的 testdata 有很多嵌套列,但是將來作業將加載的 json 檔案可能不會始終包含所有列(或者它們具有不同的資料型別)。因此,我想首先檢查列是否存在以及它具有哪種資料型別。問題:我沒有讓它作業,因為我不知道如何從資料框的嵌套模式中派生出列的資料型別。
示例:如何獲取 ecuId 的資料型別?

到目前為止,我的方法是:
df.withColumn("datatype", isinstance(col("reportData.ecus.element.ecuId"), (float, int, str, list, dict, tuple)))
或者
df.withColumn("datatype", isinstance(jsonDF.reportData.ecus.element.ecuId, (float, int, str, list, dict, tuple)))
對于這兩個版本,我都會收到錯誤訊息:“col should be Column”即使我嘗試了一個非常基本的
df.withColumn("datatype", type(jsonDF.reportData.ecus.element.ecuId))
我犯了同樣的錯誤。似乎我對如何使用嵌套結構有一個完全的誤解?你能向我解釋一下我是如何獲得資料型別的嗎?非常感謝!
uj5u.com熱心網友回復:
你得到錯誤的原因col should be Column是因為withColumn期望第二個引數是一個Column物件,而不是一個純 Python 物件。
我得到的最接近的方法有點“hacky”,通過手動決議資料幀的模式。
from pyspark.sql import functions as F
(df
.withColumn('schema', F.lit(df.dtypes[0][1]))
.withColumn('datatype', F.regexp_extract('schema', 'ecus.*.ecuId:([^>]*)', 1))
.show(10, False)
)
# Output
# ---------- ---------------------------------------- --------
# |reportData|schema |datatype|
# ---------- ---------------------------------------- --------
# |{[{1000}]}|struct<ecus:array<struct<ecuId:bigint>>>|bigint |
# ---------- ---------------------------------------- --------
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/335502.html
標籤:json 数据框 火花 apache-spark-sql 嵌套
