簡體   English   中英

map function 上 PySpark 中的 StructType

[英]map function on StructType in PySpark

我有一個 StructType 如下:

to_Schema = StructType([StructField('name', StringType(), True),
           StructField('sales', IntegerType(), True)])

dataframe_1的兩個字段都為 StringType。 所以我創建了上面的 StructType 以便我可以使用它來對dataframe_1中的字段進行類型轉換。

我可以在 Scala 中做到這一點:

val df2 = dataframe_1.selectExpr(to_Schema.map(
  col => s"CAST ( ${col.name} As ${col.dataType.sql}) ${col.name}"
): _*)

I am not able to use the same map function in python as StructType has no map function.

我試過使用for循環,但它沒有按預期工作。

我正在尋找與上述 Scala 代碼等效的 PySpark 代碼。

這將是直接翻譯:

df2 = dataframe_1.selectExpr(*[f"CAST ({c.name} AS {c.dataType.simpleString()}) {c.name}" for c in to_Schema])

可以簡化:

df2 = dataframe_1.select([col(c.name).cast(c.dataType).alias(c.name) for c in to_Schema])

但是,我更喜歡這個答案;)

下面的代碼將在 python 中實現相同的功能:

for s in to_Schema:
    df = df.withColumn(s.name, df[s.name].cast(s.dataType))

您還可以使用新架構從舊架構創建新的 dataframe,如以下答案所示:

df2 = spark.createDataFrame(dataframe_1.rdd, to_Schema)

暫無
暫無

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

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