apache-spark - 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 并获取每个项目一行?
谢谢!
解决方案
您可以简单地使用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|
+-------------+----+-----------+---+
推荐阅读
- c++ - 转换 std::vector
到 std::string_view - kubernetes - 使用多种自动伸缩机制来自动伸缩 K8s 集群
- lua - NodeMCU Lua 整数最大值为 2^31
- java - Gradle 多模块项目 - 对给定子模块执行操作的自定义任务
- python - 检测命令行参数中的空格不起作用
- javascript - 如何在单独的电子表格之间跳过重复的行值
- css - 如何让 div 滚动而不是超过页面高度?(引导程序 5)
- angular - Angular中子组件内的元素?
- google-apps-script - 使用 REST API 向 Google Chat 发送消息(Google 示例在 2020 年不起作用)
- angular - 从本地目录读取 csv 文件