在pyspark datafram上导入架构

2024-09-30 22:20:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python还不熟悉。我试图读取一个包含我的模式定义的JSON文件。它看起来像:

{
  "type" : "struct",
  "fields" : [ {
    "name" : "name",
    "type" : "string",
    "nullable" : true,
    "metadata" : { }
  }, {
    "name" : "address",
    "type" : "string",
    "nullable" : true,
    "metadata" : { }
  }, {
    "name" : "comment",
    "type" : "string",
    "nullable" : true,
    "metadata" : { }
  }
}

我有一个数据集,我需要应用上面的json模式,我尝试了以下代码:

targetDf = spark.createDataFrame(inputDf.rdd, schemaFieldsOne)

但是,这里我需要指定'schemaFieldsOne'结构类型,我想读取JSON并将其转换为Python结构类型,以便将该结构类型应用于我的数据帧(.to add)。你知道吗


Tags: 文件数据namejsontrue类型fieldsstring
1条回答
网友
1楼 · 发布于 2024-09-30 22:20:23

试试这个

import pyspark.sql.types as T
import pyspark.sql.functions as F

with open('./schema.txt', 'r') as S:  # path to your schema file
    saved_schema = json.load(S)

schema = T.StructType.fromJson(json.loads(saved_schema))

df = spark.createDataFrame(yourRdd, schema)

相关问题 更多 >