将具有结构数组的列扩展为新列

Bur*_*rke 4 apache-spark pyspark

我有一个带有单列的 DataFrame,它是一个结构数组

df.printSchema()
root
 |-- dataCells: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- label: string (nullable = true)
 |    |    |-- value: string (nullable = true)
Run Code Online (Sandbox Code Playgroud)

一些示例数据可能如下所示:

df.first()
Row(dataCells=[Row(label="firstName", value="John"), Row(label="lastName", value="Doe"), Row(label="Date", value="1/29/2018")])
Run Code Online (Sandbox Code Playgroud)

我试图弄清楚如何通过将每个结构转换为命名列来重新格式化此 DataFrame。我想要一个像这样的数据框:

------------------------------------
| firstName | lastName | Date      |
------------------------------------
| John      | Doe      | 1/29/2018 |
| ....      | ...      | ...       |
Run Code Online (Sandbox Code Playgroud)

我已经尝试了我能想到的一切,但还没有弄清楚。

hi-*_*zir 7

只需爆炸并选择*

from pyspark.sql.functions import explode, first, col, monotonically_increasing_id

df = spark.createDataFrame([
  Row(dataCells=[Row(label="firstName", value="John"), Row(label="lastName", value="Doe"), Row(label="Date", value="1/29/2018")])
])

long = (df
   .withColumn("id", monotonically_increasing_id())
   .select("id", explode("dataCells").alias("col"))
   .select("id", "col.*"))
Run Code Online (Sandbox Code Playgroud)

和pivot:

long.groupBy("id").pivot("label").agg(first("value")).show()
# +-----------+---------+---------+--------+                                      
# |         id|     Date|firstName|lastName|
# +-----------+---------+---------+--------+
# |25769803776|1/29/2018|     John|     Doe|
# +-----------+---------+---------+--------+
Run Code Online (Sandbox Code Playgroud)

你也可以:

from pyspark.sql.functions import udf

@udf("map<string,string>")
def as_map(x):
    return dict(x)

cols = [col("dataCells")[c].alias(c) for c in ["Date", "firstName", "lastName"]]
df.select(as_map("dataCells").alias("dataCells")).select(cols).show()

# +---------+---------+--------+
# |     Date|firstName|lastName|
# +---------+---------+--------+
# |1/29/2018|     John|     Doe|
# +---------+---------+--------+
Run Code Online (Sandbox Code Playgroud)

参考: