簡體   English   中英

更改 spark dataframe 列的架構

[英]Change schema of spark dataframe column

我有一個 pyspark dataframe 列“學生”。

一項數據如下:

{
   "Student" : {
       "m" : {
           "name" : {"s" : "john"},
           "score": {"s" : "165"}
       }
   }
}

我想更改此列的架構,以便條目如下所示:

{
    "Student" : 
    {
        "m" : 
        {
            "StudentDetails" : 
            {
                "m" : 
                {
                    "name" : {"s" : "john"},
                    "score": {"s" : "165"}
                }
            }
        }
    } 
}

問題是Student字段也可以是dataframe中的null。 所以我想保留 null 值,但更改不是 null 值的架構。 我在上述過程中使用了 udf 。

        def Helper_ChangeSchema(row):
            #null check
            if row is None:
                return None
            #change schema
            data = row.asDict(True)
            return {"m":{"StudentDetails":data}}

但 udf 是火花的黑匣子。 有沒有任何方法可以使用內置的 spark 函數或 sql 查詢來做同樣的事情。

它的工作原理與此答案完全相同。 只需在結構中添加另一個嵌套級別:

作為 SQL 表達式:

processedDf = df.withColumn("student", F.expr("named_struct('m', named_struct('student_details', student))"))

或在 Python 代碼中使用結構 function

processedDf = df.withColumn("student", F.struct(F.struct(F.col("student")).alias('m')))

兩個版本的結果相同:

root
 |-- student: struct (nullable = false)
 |    |-- m: struct (nullable = false)
 |    |    |-- student_details: struct (nullable = true)
 |    |    |    |-- m: struct (nullable = true)
 |    |    |    |    |-- name: struct (nullable = true)
 |    |    |    |    |    |-- s: string (nullable = true)
 |    |    |    |    |-- score: struct (nullable = true)
 |    |    |    |    |    |-- s: string (nullable = true)

這兩種方法也適用於空行。 使用此輸入數據

data ='{"student" : {"m" : {"name" : {"s" : "john"},"score": {"s" : "165"}}}}'
data2='{"student": null }'
df = spark.read.json(sc.parallelize([data, data2]))

processedDf.show(truncate=False)打印

+---------------------+
|student              |
+---------------------+
|[[[[[john], [165]]]]]|
|[[]]                 |
+---------------------+


編輯:如果整行應該設置為 null 而不是結構的字段,您可以添加一個when

processedDf = df.withColumn("student", F.when(F.col("student").isNull(), F.lit(None)).otherwise(F.struct(F.struct(F.col("student")).alias('m'))))

這將導致相同的架構,但 null 行的 output 不同:

+---------------------+
|student              |
+---------------------+
|[[[[[john], [165]]]]]|
|null                 |
+---------------------+

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM