【问题标题】:Data type mismatch: cannot cast struct for Pyspark struct field cast数据类型不匹配:无法为 Pyspark 结构字段转换转换结构
【发布时间】:2021-06-06 09:04:39
【问题描述】:

我面临一个异常,我有一个数据框,其列"hid_tagged" 作为结构数据类型,我的要求是通过将"hid_tagged" 附加到结构字段名称来更改列"hid_tagged" 结构模式,如下所示。我正在执行以下步骤并得到“数据类型不匹配:无法转换结构”异常。

你能告诉我我在这里缺少什么吗?

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

org.apache.spark.sql.AnalysisException: 无法解析 '`hid_tagged`'由于数据类型不匹配:无法转换 struct&

我能够使用以下 udf 生成预期的结构架构更改:

用于模式转换的 UDF:

from pyspark.sql.types import StructField
from pyspark.sql.types import StructType

def transform_schema(schema):

  if schema == None:
    return StructType()

  updated = []
  for f in schema.fields:
    if isinstance(f.dataType, StructType):
      
      updated.append(StructField(f.name, transform_schema(f.dataType)))
      
    else:
      
      updated.append(StructField(str("hid_tagged"+f.name),f.dataType, f.nullable))

  return StructType(updated)

源结构架构:

hid_tagged:struct
    field_1:long
    field_2:long
    field_3:string
    field_4:array
        element:string
    field_5:string
    field_6:string
    field_7:long
    field_8:long
    field_9:long
    field_10:boolean
    field_11:string
    field_12:long
    field_13:long
    field_14:long
    field_15:long
    field_16:long
    field_17:long
    field_18:long
    field_19:long
    field_20:long

预期的结构模式:

hid_tagged:struct
    hid_tagged_field_1:long
    hid_tagged_field_2:long
    hid_tagged_field_3:string
    hid_tagged_field_4:array
        element:string
    hid_tagged_field_5:string
    hid_tagged_field_6:string
    hid_tagged_field_7:long
    hid_tagged_field_8:long
    hid_tagged_field_9:long
    hid_tagged_field_10:boolean
    hid_tagged_field_11:string
    hid_tagged_field_12:long
    hid_tagged_field_13:long
    hid_tagged_field_14:long
    hid_tagged_field_15:long
    hid_tagged_field_16:long
    hid_tagged_field_17:long
    hid_tagged_field_18:long
    hid_tagged_field_19:long
    hid_tagged_field_20:long

【问题讨论】:

    标签: python apache-spark pyspark apache-spark-sql schema


    【解决方案1】:

    试试这个:

    df2 = df.select(col("hid_tagged").cast(transform_schema(df.schema)['hid_tagged'].dataType))
    

    transform_schema(df.schema) 返回整个数据帧的转换模式。您需要在转换之前选择hid_tagged 列的数据类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多