如何展平结构数组?

How to flatten array of struct?

如何从这里更改 PySpark 中的模式

|-- id: string (nullable = true)
|-- device: array (nullable = true)
|    |-- element: struct (containsNull = true)
|    |    |-- device_vendor: string (nullable = true)
|    |    |-- device_name: string (nullable = true)
|    |    |-- device_manufacturer: string (nullable = true)

至此

|-- id: string (nullable = true)
|-- device_vendor: string (nullable = true)
|-- device_name: string (nullable = true)
|-- device_manufacturer: string (nullable = true)

首先,使用 element_at 获取第一个数组的元素,然后使用 * 从结构中提取所有元素。

df = df.withColumn('d', F.element_at('device', 1))
df = df.select('id', 'd.*')

结合使用 explode* 选择器:

import pyspark.sql.functions as F

df_flat = df.withColumn('device_exploded', F.explode('device'))
            .select('id', 'device_exploded.*')

df_flat.printSchema()
# root
#  |-- id: string (nullable = true)
#  |-- device_vendor: string (nullable = true)
#  |-- device_name: string (nullable = true)
#  |-- device_manufacturer: string (nullable = true)

explode 为 array-valued 列的每个元素创建一个单独的记录,重复其他列的值。 column.* 选择器将 struct-valued 列的所有字段转换为单独的列。