首页 > 解决方案 > json 文件到 pyspark 数据帧

问题描述

我已经下载了一个 json 文件,我正在尝试将它放入 DataFrame 中,以进行一些分析。

raw_constructors = spark.read.json("/constructors.json")

当我制作时raw_constructors.show() ,我只得到一列和一行。

+--------------------+
|              MRData|
+--------------------+
|{{[{adams, Adams,...|
+--------------------+

因此,当我询问 json 文件的架构时 raw_constructors.printSchema()

我懂了:

root
 |-- MRData: struct (nullable = true)
 |    |-- ConstructorTable: struct (nullable = true)
 |    |    |-- Constructors: array (nullable = true)
 |    |    |    |-- element: struct (containsNull = true)
 |    |    |    |    |-- constructorId: string (nullable = true)
 |    |    |    |    |-- name: string (nullable = true)
 |    |    |    |    |-- nationality: string (nullable = true)
 |    |    |    |    |-- url: string (nullable = true)
 |    |-- limit: string (nullable = true)
 |    |-- offset: string (nullable = true)
 |    |-- series: string (nullable = true)
 |    |-- total: string (nullable = true)
 |    |-- url: string (nullable = true)
 |    |-- xmlns: string (nullable = true)

我正在使用 pyspark。

如何获取包含 4 列的 dataFrame:constructorId、name、nationality、url 并获取每个项目一行?

谢谢!

标签: apache-sparkpysparkapache-spark-sqljupyter-notebookjupyter

解决方案


您可以简单地使用explode将数组分解为多行

from pyspark.sql import functions as F

(df
    .select(F.explode('MRData.ConstructorTable.Constructors').alias('tmp'))
    .select('tmp.*')
    .show()
)

+-------------+----+-----------+---+
|constructorId|name|nationality|url|
+-------------+----+-----------+---+
|           i1|  n1|         y1| u1|
|           i2|  n2|         y2| u2|
+-------------+----+-----------+---+

推荐阅读