[英]Data type mismatch: cannot cast struct for Pyspark struct field cast
我遇到了一個異常,我有一個 dataframe,其中有一列"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
嘗試這個:
df2 = df.select(col("hid_tagged").cast(transform_schema(df.schema)['hid_tagged'].dataType))
transform_schema(df.schema)
返回整個 dataframe 的轉換模式。 您需要在轉換之前選擇hid_tagged
列的數據類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.