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

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

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

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

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

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
j91ykkif

j91ykkif1#

试试这个:

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

相关问题