用于删除复杂 Json 模式中的列的 Pyspark 代码

问题描述 投票:0回答:1

团队

我是 Pyspark 编程的初学者

我正在尝试从下面架构中存在的数组列中删除“ProductEntityCode”。此列嵌套在 ProductSaleData(一个数组)内,该数组嵌套在 EventPayload(一个结构体)内。

任何人都可以告诉我如何删除这个嵌套的 ProductEntityCode,同时保持其他列完好无损。真的会很有帮助。

 |-- EventId: string (nullable = true)
 |-- EventPayload: struct (nullable = true)
 |    |-- AccountId: long (nullable = true)
 |    |-- ProductSaleData: array (nullable = true)
 |    |    |-- element: struct (containsNull = true)
 |    |    |    |-- PortionId: long (nullable = true)
 |    |    |    |-- PortionName: string (nullable = true)
 |    |    |    |-- **ProductEntityCode: long (nullable = true)**
 |    |    |    |-- ProductReference: string (nullable = true)
 |    |    |    
 |    |-- SiteId: long (nullable = true)
 |    |-- SiteReference: string (nullable = true)
 |   
 |-- EventProcessedUtcTime: string (nullable = true)
 
dataframe pyspark databricks
1个回答
0
投票

您可以使用

withField
更新列的子字段,并使用
transform
修改数组中的元素。要删除结构中的字段,请使用
dropFields

df = (df.withColumn("EventPayload", 
                    (F.col("EventPayload")
                     .withField("ProductSaleData", 
                                F.transform("EventPayload.ProductSaleData", 
                                            lambda x: x.dropFields("ProductEntityCode"))))
                   )
)
© www.soinside.com 2019 - 2024. All rights reserved.