【问题标题】:json file into pyspark dataFramejson 文件到 pyspark 数据帧
【发布时间】:2021-08-06 15:28:47
【问题描述】:

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

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

当我创建raw_constructors.show() 时,我只得到一列一行。

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

所以当我用 raw_constructors.printSchema()询问json文件的架构时

我知道了:

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 并获取每个项目的一行?

谢谢!

【问题讨论】:

  • 你想把所有东西都展平还是只需要constructorId、name、nationality、url列?
  • @Suresh 你是莱特,列以及它们各自的行。谢谢!
  • 请举个输入、输出的例子,我们会更容易提供帮助
  • @pltc 我已经编辑了我的问题。我希望它有点帮助。

标签: apache-spark pyspark apache-spark-sql jupyter-notebook jupyter


【解决方案1】:

您可以简单地使用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|
+-------------+----+-----------+---+

【讨论】:

  • 谢谢@pltc :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多