如何从PySpark中的数据框中获取模式定义?

问题描述 投票:8回答:3

在PySpark中,您可以定义一个架构并使用此预定义的架构读取数据源,例如g。:

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-spark dataframe pyspark schema azure-databricks
3个回答
10
投票

是的,有可能。使用DataFrame.schema DataFrame.schema

property

[将此DataFrame的架构作为pyspark.sql.types.StructType返回。

property

1.3版中的新功能。

模式schema,如果需要。


2
投票

您可以为现有数据框重用架构

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

只需使用df.schema即可获得数据框的基础架构

can be also exported to JSON and imported back

0
投票

下面的代码将为您提供已知数据帧的格式良好的表格模式定义。当您有非常多的列并且编辑繁琐时,这很有用。然后,您现在可以将其应用于新的数据框并手动编辑您可能想要相应的任何列。

l = [('Ankita',25,'F'),('Jalfaizy',22,'M'),('saurabh',20,'M'),('Bala',26,None)]
people_rdd=spark.sparkContext.parallelize(l)
schemaPeople = people_rdd.toDF(['name','age','gender'])

schemaPeople.show()

+--------+---+------+
|    name|age|gender|
+--------+---+------+
|  Ankita| 25|     F|
|Jalfaizy| 22|     M|
| saurabh| 20|     M|
|    Bala| 26|  null|
+--------+---+------+

spark.createDataFrame(people_rdd,schemaPeople.schema).show()

+--------+---+------+
|    name|age|gender|
+--------+---+------+
|  Ankita| 25|     F|
|Jalfaizy| 22|     M|
| saurabh| 20|     M|
|    Bala| 26|  null|
+--------+---+------+

然后从这里,您有了新的架构:

schemaPeople.schema

StructType(List(StructField(name,StringType,true),StructField(age,LongType,true),StructField(gender,StringType,true)))
© www.soinside.com 2019 - 2024. All rights reserved.