在PySpark中,您可以定义一个架构并使用此预定义的架构读取数据源,例如:
Schema = StructType([ StructField("temperature", DoubleType(), True),
StructField("temperature_unit", StringType(), True),
StructField("humidity", DoubleType(), True),
StructField("humidity_unit", StringType(), True),
StructField("pressure", DoubleType(), True),
StructField("pressure_unit", StringType(), True)
])
对于某些数据源,可以从数据源推断模式并使用此模式定义获取数据框。
是否可以从以前推断过数据的数据帧中获得模式定义(以上述形式)?
df.printSchema()
将模式打印为树,但是我需要重用该模式(如上定义),因此我可以从以前从另一个数据源推断出的该模式读取一个数据源。
是的,有可能。采用DataFrame.schema
property
schema
以pyspark.sql.types.StructType的形式返回此DataFrame的架构。
>>> df.schema StructType(List(StructField(age,IntegerType,true),StructField(name,StringType,true)))
1.3版的新功能。
架构也可以导出为JSON,并在需要时导入回来。