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

PySpark中字符串转整数结果全为Null的问题求助

解决PySpark字符串转整数全为Null的问题

以下是几种常见原因及对应解决方法:

  • 字符串包含隐藏非数字字符
    很多时候字符串表面看是纯数字,但实际带有空格、制表符或其他不可见字符,导致转换失败。先清洗字符串再转换:

    from pyspark.sql.functions import regexp_replace, trim
    from pyspark.sql.types import IntegerType
    
    # 方法1:去除首尾空格
    df = df.withColumn("int_column", trim(col("string_column")).cast(IntegerType()))
    
    # 方法2:移除所有非数字字符
    df = df.withColumn("int_column", regexp_replace(col("string_column"), "[^0-9]", "").cast(IntegerType()))
    
  • 数字超出IntegerType范围
    PySpark的IntegerType是32位整数,范围为 -2147483648 到 2147483647。如果你的数字超过这个上限,转换会返回Null,此时改用LongType:

    from pyspark.sql.types import LongType
    
    df = df.withColumn("int_column", col("string_column").cast(LongType()))
    
  • 列名不匹配
    检查代码中使用的列名是否和DataFrame实际列名一致。比如你示例中列名是string_column,但代码里写的是previous_id,如果列名错误会导致转换失败。可以用df.columns查看所有列名确认。

  • 存在非数字格式的行
    排查是否有其他行包含非数字内容(比如空字符串、字母):

    # 查看非纯数字的行
    df.filter(~col("string_column").rlike("^[0-9]+$")).show()
    

    对这些异常行做过滤或处理后再转换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 07:20:36