簡體   English   中英

在 pyspark dataframe 上導入架構

[英]Import Schema on pyspark dataframe

我是 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 結構類型,以便我可以將該 StructType 應用於我的數據幀(添加)。

嘗試這個

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM