为什么空值在删除 PySpark 后仍在列中

Why Null Value is still in the column after dropping it PySpark

我正在 Jupyter Notebook 上使用 Python PySpark,我正在尝试删除 "Age".

列中的所有空值

我尝试了这两种方法,其中 NONE 行得通:

new_df.na.drop(subset=["Age"])
new_df.dropna()

这是我目前正在使用的代码:

import pyspark.sql.functions as f

new_df = new_df.withColumn(
  "Age",
  f.when(
    (f.col("Age") >= 0) & 
    (f.col("Age") <= 95), f.col("Age")).otherwise(f.lit(None))
)

new_df.dropna()
new_df.select('Age').distinct().show(1000, False)

我不确定我做错了什么,或者空值没有被删除的错误在哪里,请告诉我如何解决这个问题。提前致谢

将 new_df.dropna() 分配给新的 ref。 dropna() 处理传入的数据帧并输出新处理的数据帧。这不是就地操作。因此,修改您的代码如下-

import pyspark.sql.functions as f

new_df = new_df.withColumn(
  "Age",
  f.when(
    (f.col("Age") >= 0) & 
    (f.col("Age") <= 95), f.col("Age")).otherwise(f.lit(None))
)

na_df = new_df.dropna()
na_df.select('Age').distinct().show(1000, False)

请注意-

na_df = new_df.dropna()

ref - https://spark.apache.org/docs/latest/api/python/pyspark.sql.html?highlight=na#pyspark.sql.DataFrame.na