如何删除 PySpark DataFrame 中具有空值的所有列?

Mat*_*hew 8 python apache-spark apache-spark-sql pyspark

我有一个很大的数据集,我想删除包含null值的列并返回一个新的数据框。我怎样才能做到这一点?

以下仅删除包含null.

df.where(col("dt_mvmt").isNull()) #doesnt work because I do not have all the columns names or for 1000's of columns
df.filter(df.dt_mvmt.isNotNull()) #same reason as above
df.na.drop() #drops rows that contain null, instead of columns that contain null
Run Code Online (Sandbox Code Playgroud)

例如

a |  b  | c
1 |     | 0
2 |  2  | 3
Run Code Online (Sandbox Code Playgroud)

在上述情况下,它将删除整列,B因为其中一个值为空。

Flo*_*ian 10

这是删除所有具有 NULL 值的列的一种可能方法:有关计算每列 NULL 值的代码的来源,请参见此处

import pyspark.sql.functions as F

# Sample data
df = pd.DataFrame({'x1': ['a', '1', '2'],
                   'x2': ['b', None, '2'],
                   'x3': ['c', '0', '3'] })
df = sqlContext.createDataFrame(df)
df.show()

def drop_null_columns(df):
    """
    This function drops all columns which contain null values.
    :param df: A PySpark DataFrame
    """
    null_counts = df.select([F.count(F.when(F.col(c).isNull(), c)).alias(c) for c in df.columns]).collect()[0].asDict()
    to_drop = [k for k, v in null_counts.items() if v > 0]
    df = df.drop(*to_drop)
    return df

# Drops column b2, because it contains null values
drop_null_columns(df).show()
Run Code Online (Sandbox Code Playgroud)

前:

+---+----+---+
| x1|  x2| x3|
+---+----+---+
|  a|   b|  c|
|  1|null|  0|
|  2|   2|  3|
+---+----+---+
Run Code Online (Sandbox Code Playgroud)

后:

+---+---+
| x1| x3|
+---+---+
|  a|  c|
|  1|  0|
|  2|  3|
+---+---+
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!