我得到了一個具有以下架構的結構列(來自 json):
struct_col_name
| |-- 2053771759: struct (nullable = true)
| | |-- col1: long (nullable = true)
| | |-- col2: string (nullable = true)
| | |-- col3: long (nullable = true)
| | |-- col4: string (nullable = true)
| |-- 2053771760: struct (nullable = true)
| | |-- col1: long (nullable = true)
| | |-- col2: string (nullable = true)
| | |-- col3: long (nullable = true)
| | |-- col4: string (nullable = true)
| |-- 2053771761: struct (nullable = true)
| | |-- col1: long (nullable = true)
| | |-- col2: string (nullable = true)
| | |-- col3: long (nullable = true)
| | |-- col4: string (nullable = true)
由于所有內部 strcuts 具有相同的欄位,我想將架構轉換為類似的內容,并將id(2053771759例如)添加為每個元素的欄位。
通過這樣做,我將能夠將列分解為行。
struct_col_name
| |-- element: struct: struct (nullable = true)
| | | |-- col1: long (nullable = true)
| | | |-- col2: string (nullable = true)
| | | |-- col3: long (nullable = true)
| | | |-- col4: string (nullable = true)
| | | |-- id: long (nullable = true)
知道我該怎么做嗎?或者以任何其他方式爆炸列?
uj5u.com熱心網友回復:
首先,您可以IDs使用df.select("struct_col_name.*")資料框的模式獲取串列。然后,您可以遍歷該串列以通過將id欄位添加到現有欄位并創建結構列陣列來更新每個結構。最后,分解陣列列以逐行獲得一個結構體。
像這樣的東西:
from pyspark.sql import functions as F
inner_fields = ["col1", "col2", "col3", "col4"]
ids = df.select("struct_col_name.*").columns
df = df.select(
F.explode(F.array(*[
F.struct(*[
F.col(f"struct_col_name.{i}.{c}") for c in inner_fields
], F.lit(i).alias(i))
for i in ids
])).alias("struct_col_name")
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/394033.html
標籤:Python 阿帕奇火花 火花 apache-spark-sql
上一篇:在哪里可以找到JavaMapWithStateSuite.java中參考的JavaTestUtils和BatchCounter依賴項?
