首页 > 解决方案 > 删除空列的快速方法 [PySpark]

问题描述

有没有一种简单的方法可以在 pyspark 中删除巨大数据集(300+ col >100k 行)的空列?比如df.dropna(axis=1,how='all')在 Python 中

标签: pysparkis-emptycol

解决方案


是的,您可以简单地使用此处的答案。我threshold给它添加了一个参数:

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, threshold=0):
    """
    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 > threshold]
    df = df.drop(*to_drop)
    return df

# Drops column b2, because it contains null values
drop_null_columns(df).show()

输出

+---+---+
| x1| x3|
+---+---+
|  a|  c|
|  1|  0|
|  2|  3|
+---+---+

列 x2 已被删除。

您可以在使用threshold=df.count()时使用它


推荐阅读