You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PySpark嵌套数组类型转换报错:ArrayType(NullType)转IntegerType

解决Spark DataFrame嵌套数组列的类型转换问题

错误原因

你调用cast()时传入了StructField对象,这是错误的——cast()方法只接受DataType类型的参数,StructField是用来定义DataFrame schema结构的,不能直接用于字段类型转换。

修正方案

直接定义嵌套的ArrayType作为目标类型,不需要包装成StructField:

# 正确的目标类型:两层ArrayType,内层元素为IntegerType
desired_type = ArrayType(ArrayType(IntegerType(), True), True)
df = df.withColumn("nums", col("nums").cast(desired_type))

完整可运行代码

from pyspark.sql import SparkSession
from pyspark.sql.types import StructType, StructField, StringType, ArrayType, NullType, IntegerType
from pyspark.sql.functions import col

spark = SparkSession.builder.appName("NestedArrayCast").getOrCreate()

data2 = [
    ("James", [[None, None], [None, None]]),
    ("Michael", [[None, None], [None, None]]),
]

schema = StructType(
    [
        StructField("firstname", StringType(), True),
        StructField("nums", ArrayType(ArrayType(NullType(), True), True), True),
    ]
)

df = spark.createDataFrame(data=data2, schema=schema)

# 执行类型转换
desired_type = ArrayType(ArrayType(IntegerType(), True), True)
df = df.withColumn("nums", col("nums").cast(desired_type))

# 查看结果
df.show()
df.printSchema()

验证结果

运行后printSchema()会输出:

root
 |-- firstname: string (nullable = true)
 |-- nums: array (nullable = true)
 |    |-- element: array (containsNull = true)
 |    |    |-- element: integer (containsNull = true)

说明nums列已成功转换为ArrayType(ArrayType(IntegerType))类型。

内容的提问来源于stack exchange,提问作者Powers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 19:17:24