You need to enable JavaScript to run this app. PySpark使用StructType将RDD转DataFrame出现类型不匹配错误
优惠活动
大模型
产品
解决方案
定价
更多

PySpark使用StructType将RDD转DataFrame出现类型不匹配错误

RDD搭配自定义StructType Schema转DataFrame的报错修复

报错根源

你运行代码时抛出的核心错误如下:

org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 5.0 failed 1 times, most recent failure: Lost task 0.0 in stage 5.0 (TID 7) (ip-10-172-239-64.us-west-2.compute.internal executor driver): org.apache.spark.api.python.PythonException: 'TypeError: field eid: IntegerType can not accept object '100' in type <class 'str'>'. Full traceback below:

拆分文本得到的empdata RDD中,所有元素经过split(",")处理后都是字符串类型。但你定义的Schema里eid、esal要求是整数类型,revsal要求是浮点数类型——PySpark做Schema校验时,不会自动把强字符串格式的'100'转换为整数/浮点数,因此抛出类型不兼容异常。

修复方案

完全不需要改成Spark CSV读取的方式,保持你原本用RDD + 自定义StructType Schema的路径即可,只需要在RDD的转换阶段做字段类型映射,匹配Schema的类型要求:

  • 拆分完逗号分隔的文本后,按照Schema的字段顺序,把对应位置的字符串值转换为匹配的Python原生类型:整数字段转int,浮数字段转float,文本字段保留str
  • 提前兼容空值场景:如果文本行内存在空字段,要把空字符串转为Python的None,避免类型转换时直接报错

修正后的完整可运行代码:

from pyspark.sql import SparkSession
from pyspark.sql.types import StructType, StructField, StringType, IntegerType, DoubleType

spark = SparkSession \
        .builder \
        .appName("pyspark") \
        .master("local[3]") \
        .getOrCreate()  

# 读取文件后拆分字段、逐字段做类型转换匹配Schema
empdata = spark.sparkContext.textFile("/FileStore/tables/empdatarevised.txt")\
    .map(lambda x: x.split(","))\
    .map(lambda row: (
        int(row[0]),    # eid 匹配IntegerType
        row[1].strip(), # ename 匹配StringType
        row[2].strip(), # edept 匹配StringType
        int(row[3]),    # esal 匹配IntegerType
        float(row[4])   # revsal 匹配DoubleType
    ))

# 保持原有定义的Schema逻辑不变即可
schema = StructType([
        StructField("eid",IntegerType(),True),
        StructField("ename",StringType(),True),
        StructField("edept",StringType(),True),
        StructField("esal", IntegerType(), True),
        StructField("revsal", DoubleType(), True),
        ])

df = spark.createDataFrame(data=empdata,schema=schema)
df.show()

可选优化

如果担心后续调整Schema字段顺序时出现列值错位的问题,可以把RDD的行转换为带字段名的Row对象,实现字段名和值的映射匹配,不依赖固定列顺序,代码会更健壮。对应的RDD转换逻辑替换为以下代码即可:

from pyspark.sql import Row

empdata = spark.sparkContext.textFile("/FileStore/tables/empdatarevised.txt")\
    .map(lambda x: x.split(","))\
    .map(lambda row: Row(
        eid=int(row[0]),
        ename=row[1].strip(),
        edept=row[2].strip(),
        esal=int(row[3]),
        revsal=float(row[4])
    ))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.27 20:27:04