pyspark: the number of entries in a column which are null or not

There's were a handful of resources describing how to count the number of null values in a pyspark dataframe. For example this Stack Overflow thread which asks for the number of null (and nan) values for each column in a pyspark dataframe. Thus given the total number of entries in the dataframe, one could indirectly compute the number of not null values (by taking the difference). However, I sought after a solution which would simultaneously output both the number of null and not null values (for a single column).

Eventually, I wrote the following possible solution:
(
  df
  .select(df.MY_COLUMN_NAME.isNull().alias(MY_COLUMN_NAME))
  .groupby(MY_COLUMN_NAME)
  .count()
  .show()
)

In contrast, the following is the solution with just the count of null values:
(
  df
  .select(count(when(df.MY_COLUMN_NAME.isNull()).alias(MY_COLUMN_NAME))
  .show()
)

Of course the advantage of the latter was it's ability to summarize across every column:
(
  df
  .select([count(when(col(c).isNull()).alias(c) for c in df.columns])
  .show()
)

[20200813][20200923 Edit]

Comments

  1. The article demonstrates a simple PySpark technique for counting both null and non-null values in a DataFrame column using isNull(), groupBy(), and count(). This approach helps data engineers and analysts quickly evaluate data quality by identifying missing values before performing data transformation, analytics, or machine learning. Understanding how to validate datasets efficiently is an essential part of building reliable big data processing pipelines.

    PySpark is a powerful framework for distributed data processing, enabling organizations to analyze massive datasets efficiently across clusters. Its DataFrame API provides scalable operations for filtering, aggregation, data validation, and ETL workflows, making it a key technology for modern big data analytics. Students interested in implementing enterprise-scale analytics solutions can explore Big Data Projects, featuring practical implementations involving Apache Spark, Hadoop, distributed computing, ETL pipelines, and cloud-based data processing.

    ReplyDelete

Post a Comment

Popular posts from this blog

Getting to know... D3

Parquet + PySpark (= Speed)

Observable HQ: dropdown input, d3 transition, and viewof