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

PySpark如何删除指定单列包含null值的对应行及列

PySpark 指定单列空值处理实现方案

两类核心操作实现

操作1:删除指定单列包含null值的对应行

仅以目标列是否存在null作为行删除的判断标准,其他列的null值不会触发行删除,两种实现方式:

  • 基于na.drop的简洁写法,适合多列批量空值行过滤场景:
    # 替换target_col为你要处理的指定列名
    df = df.na.drop(subset=["target_col"])
    
  • 基于filter的灵活写法,可叠加其他过滤条件:
    df = df.filter(df.target_col.isNotNull())
    

操作2:删除包含null值的指定单列

判断目标列是否存在任意null值,若存在则删除整个目标列,否则保留原列:

target_col = "target_col"
# 统计目标列的空值行数
null_cnt = df.filter(df[target_col].isNull()).count()
# 若存在空值则删除整列
if null_cnt > 0:
    df = df.drop(target_col)

单独删除指定单列含null值对应行的完整示例

可直接运行的测试代码如下:

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

# 初始化Spark会话
spark = SparkSession.builder.appName("drop_null_row_demo").getOrCreate()

# 构造测试数据集
test_schema = StructType([
    StructField("id", IntegerType(), nullable=True),
    StructField("target_col", StringType(), nullable=True),
    StructField("other_col", StringType(), nullable=True)
])
test_data = [
    (1, "正常值1", "其他值1"),
    (2, None, "其他值2"),
    (3, "正常值2", None),
    (4, None, "其他值4"),
    (5, "正常值3", "其他值5")
]
df = spark.createDataFrame(test_data, schema=test_schema)

# 执行空值行删除,仅判断target_col列
df_result = df.na.drop(subset=["target_col"])

# 输出结果验证,id为2、4的行已被删除,other_col列的空值不影响判断
df_result.show()

注意:如果需要同时对多列做空值行删除,只需将subset参数后的列表修改为对应列名集合即可


内容的提问来源于stack exchange,提问作者S. Bharanidharan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 04:54:03