PySpark3.0读取CSV时空字符串被识别为null,如何保留原始空字符串?
解决方案
你的配置不生效主要有两个核心原因:
- Spark 3.x 版本已弃用
treatEmptyValuesAsNulls参数,该参数不再生效 - 开启
inferSchema自动推断类型时,age列会被识别为整数类型,整数类型本身无法存储空字符串,会被强制转换为null
具体操作
步骤1:自定义Schema
首先手动定义读取Schema,将需要保留空字符串的字段设置为StringType:
from pyspark.sql.types import StructType, StructField, IntegerType, StringType custom_schema = StructType([ StructField("ID", IntegerType(), nullable=True), StructField("name", StringType(), nullable=True), # 如果需要保留age列的空字符串,设置为StringType;如果接受age列空值为null,可保留为IntegerType StructField("age", StringType(), nullable=True) ])
步骤2:配置CSV读取参数
将nullValue设置为数据中绝对不会出现的占位字符串,emptyValue设置为空字符串:
df = spark.read \ .option("delimiter", "^") \ .option("quote","") \ .option("header", "true") \ .option("nullValue", "__UNIQUE_MARKER_THAT_NEVER_APPEARS_IN_DATA__") \ .option("emptyValue", "") \ .schema(custom_schema) \ .csv("你的CSV文件路径")
可选:后续类型转换
如果需要age列最终为数值类型,可在读取完成后手动做转换:
from pyspark.sql.functions import col, when # 按需调整转换逻辑,这里是将空字符串转为null,你也可以转为0等默认值 df = df.withColumn("age", when(col("age") == "", None).otherwise(col("age").cast(IntegerType())))
执行以上操作后,CSV中的空单元格会被读取为原始空字符串"",不会被自动转换为null。
内容的提问来源于stack exchange,提问作者milton
相关产品推荐
相关产品推荐

