![](/img/trans.png)
[英]PySpark How to parse and get field names from Dataframe schema's StructType Object
[英]How to get the schema definition from a dataframe in 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()
將模式打印為樹,但我需要重用模式,將其定義如上,因此我可以讀取具有此模式的數據源,該模式之前已從另一個數據源推斷出來。
對的,這是可能的。 使用DataFrame.schema
property
schema
將此 DataFrame 的架構作為 pyspark.sql.types.StructType 返回。
>>> df.schema StructType(List(StructField(age,IntegerType,true),StructField(name,StringType,true)))
1.3 版中的新功能。
如果需要,模式也可以導出為 JSON 並導入回來。
您可以為現有的 Dataframe 重用架構
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|
+--------+---+------+
只需使用 df.schema 即可獲取數據框的底層架構
schemaPeople.schema
StructType(List(StructField(name,StringType,true),StructField(age,LongType,true),StructField(gender,StringType,true)))
下面的代碼將為您提供已知數據幀的格式良好的表格模式定義。 當您有非常多的列並且編輯很麻煩時,這非常有用。 然后,您現在可以將其應用於新的數據框並手動編輯您可能想要的任何列。
from pyspark.sql.types import StructType
schema = [i for i in df.schema]
然后從這里開始,您有了新的架構:
NewSchema = StructType(schema)
如果您正在尋找來自 PySpark 的 DDL 字符串:
df: DataFrame = spark.read.load('LOCATION')
schema_json = df.schema.json()
ddl = spark.sparkContext._jvm.org.apache.spark.sql.types.DataType.fromJson(schema_json).toDDL()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.