数据类型不匹配:无法为pyspark struct字段强制转换struct

jhiyze9q  于 2021-07-12  发布在  Spark
关注(0)|答案(1)|浏览(462)

我面临一个例外,我有一个列的Dataframe "hid_tagged" 作为struct数据类型,我的要求是更改列 "hid_tagged" 通过附加 "hid_tagged" 结构字段名,如下所示。我遵循以下步骤并得到“数据类型不匹配:无法转换结构”异常。
你能告诉我我错过了什么吗。

  1. df2=df.select(col("hid_tagged").cast(transform_schema(df.schema)))

org.apache.spark.sql.analysisexception:无法解析&#39隐藏标签'由于数据类型不匹配:无法强制转换结构&
我能够使用以下自定义项生成预期的结构模式更改:
架构转换的自定义项:

  1. from pyspark.sql.types import StructField
  2. from pyspark.sql.types import StructType
  3. def transform_schema(schema):
  4. if schema == None:
  5. return StructType()
  6. updated = []
  7. for f in schema.fields:
  8. if isinstance(f.dataType, StructType):
  9. updated.append(StructField(f.name, transform_schema(f.dataType)))
  10. else:
  11. updated.append(StructField(str("hid_tagged"+f.name),f.dataType, f.nullable))
  12. return StructType(updated)

源结构架构:

  1. hid_tagged:struct
  2. field_1:long
  3. field_2:long
  4. field_3:string
  5. field_4:array
  6. element:string
  7. field_5:string
  8. field_6:string
  9. field_7:long
  10. field_8:long
  11. field_9:long
  12. field_10:boolean
  13. field_11:string
  14. field_12:long
  15. field_13:long
  16. field_14:long
  17. field_15:long
  18. field_16:long
  19. field_17:long
  20. field_18:long
  21. field_19:long
  22. field_20:long

应为结构架构:

  1. hid_tagged:struct
  2. hid_tagged_field_1:long
  3. hid_tagged_field_2:long
  4. hid_tagged_field_3:string
  5. hid_tagged_field_4:array
  6. element:string
  7. hid_tagged_field_5:string
  8. hid_tagged_field_6:string
  9. hid_tagged_field_7:long
  10. hid_tagged_field_8:long
  11. hid_tagged_field_9:long
  12. hid_tagged_field_10:boolean
  13. hid_tagged_field_11:string
  14. hid_tagged_field_12:long
  15. hid_tagged_field_13:long
  16. hid_tagged_field_14:long
  17. hid_tagged_field_15:long
  18. hid_tagged_field_16:long
  19. hid_tagged_field_17:long
  20. hid_tagged_field_18:long
  21. hid_tagged_field_19:long
  22. hid_tagged_field_20:long
j91ykkif

j91ykkif1#

试试这个:

  1. df2 = df.select(col("hid_tagged").cast(transform_schema(df.schema)['hid_tagged'].dataType))
  2. ``` `transform_schema(df.schema)` 返回整个Dataframe的转换架构。您需要选择 `hid_tagged` 铸造前的立柱。

相关问题