簡體   English   中英

從 PySpark 中的列名列表派生 structType 模式

[英]Derive structType schema from list of column names in PySpark

在 PySpark 中,我不想硬編碼模式定義,我想從下面的變量中派生模式。

mySchema=[("id","IntegerType()", True),
          ("name","StringType()", True),
          ("InsertDate","TimestampType()", True)
         ]

result = mySchema.map(lambda l: StructField(l[0],l[1],l[2]))

如何實現此邏輯以從mySchema生成structTypeSchema

預期輸出:

structTypeSchema = StructType(fields=[
                                      StructField("id", IntegerType(), True),
                                      StructField("name", StringType(), True), 
                                      StructField("InsertDate",TimestampType(), True)])

您可以嘗試以下方法:

from pyspark.sql import types as T

structTypeSchema = T.StructType(
    [T.StructField(f[0], eval(f'T.{f[1]}'), f[2]) for f in mySchema]
)

或者

from pyspark.sql.types import *
                                       
structTypeSchema = StructType(
    [StructField(f[0], eval(f[1]), f[2]) for f in mySchema]
)

暫無
暫無

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

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