首页 > 解决方案 > 如何从 PySpark 中的数据框中获取模式定义?

问题描述

在 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()将模式打印为树,但我需要重用模式,将其定义如上,因此我可以读取具有此模式的数据源,该模式之前已从另一个数据源推断。

标签: apache-sparkdataframepysparkschemaazure-databricks

解决方案


是的,有可能。采用DataFrame.schema property

schema

以 pyspark.sql.types.StructType 形式返回此 DataFrame 的架构。

>>> df.schema
StructType(List(StructField(age,IntegerType,true),StructField(name,StringType,true)))

1.3 版中的新功能。

Schema也可以导出为 JSON 并在需要时重新导入。


推荐阅读