In Polars, the count() function is used to count the number of non-null values in each column of a DataFrame. It does not return the total number of rows but instead counts non-null values per column. Null values are automatically excluded, making it a fast and efficient method for computing counts.
In this article, I will explain the count() function of a Polars DataFrame, covering its syntax, parameters, and usage and how we can return a new DataFrame with a single row, where each column displays the count of non-null values.
Key Points –
- The
count()function in Polars counts only the non-null (non-missing) values in a DataFrame or a specific column. - When applied to a DataFrame,
count()returns the count of non-null values for each column. - You can use
select(pl.col("column_name").count())to count non-null values in a specific column. - Works with all data types, including numeric, string, boolean, and datetime columns.
- The output is a new DataFrame with a single row containing the count of non-null values per column.
- Only non-null (non-
None) values are counted, making it useful for identifying missing data. df.heightreturns the total number of rows (including None values), whereasdf.count()counts only non-null values.- The function returns a new DataFrame without altering the original DataFrame.
<a id="h-polars-dataframe-count-introduction"></a>
Polars DataFrame count() Introduction
Let’s know the syntax of the polars DataFrame.count() function.
# Syntax of count()
polars.count(*columns: str) → Expr
<a id="h-parameters-of-the-polars-dataframe-count"></a>
Parameters of the Polars DataFrame.count()
It allows only one parameter.
*columns- If no columns are specified, it returns the total number of rows. You can also provide one or more column names.
<a id="h-return-value"></a>
Return Value
This function returns a new DataFrame with a single row containing the count of non-null values for each column.
<a id="h-usage-of-polars-dataframe-count-function"></a>
Usage of Polars DataFrame count() Function
The DataFrame.count() function in Polars counts the number of non-null (non-None) values in each column of a DataFrame. It returns a new DataFrame with a single row, where each column represents the count of its non-null values. It is useful for understanding data completeness and ensuring data integrity.
To run some examples of the Polars DataFrame count() function, let’s create a Polars DataFrame using data from a dictionary.
import polars as pl
technologies= ({
'Courses':["Spark","PySpark","Hadoop",None,"Python","Pandas"],
'Courses Fee' :[22000,25000,None,23000,24000,26000],
'Duration':['30days',None,'50days','30days',None,None],
'Discount':[1000,None,2300,None,1200,2500]
})
df = pl.DataFrame(technologies)
print("Original DataFrame:\n", df)
Yields below output.
When you call the df.count() function, polars counts the number of non-null values in each column of the DataFrame. This is useful for identifying missing data.
# Count non-null values in each column
df2 = df.count()
print("Count of Non-Null Values in Each Column:\n", df2)
Here,
df.count()calculates the number of non-null (non-missing) values in each column.- It ignores null values (
Nonevalues in Python) and counts only the valid data points. - The result is a single-row DataFrame showing the non-null counts for each column.
<a id="h-count-non-null-values-in-a-specific-column"></a>
Count Non-Null Values in a Specific Column
To count non-null values in a specific column of a Polars DataFrame, use the count() function along with the select() method. This approach automatically ignores null values and returns the number of non-null entries.
# Count non-null values in the "Courses Fee" column
df2 = df.select(pl.col("Courses Fee").count())
print("Count of Non-Null Values in 'Courses Fee':\n",df2)
# Count non-null values in the "Courses Fee" column
df2 = df.select(pl.count("Courses Fee"))
print("Count of Non-Null Values in 'Courses Fee':\n",df2)
# Output:
# Count of Non-Null Values in 'Courses Fee':
# shape: (1, 1)
┌─────────────┐
│ Courses Fee │
│ --- │
│ u32 │
╞═════════════╡
│ 5 │
└─────────────┘
Here,
- The
"Courses Fee"column has 5 non-null values (Noneis ignored). - The output is a single-row DataFrame with the count of non-null values.
<a id="h-count-non-null-values-in-multiple-columns"></a>
Count Non-Null Values in Multiple Columns
You can also count non-null values in multiple columns of a Polars DataFrame, we use the count() function along with the select() method.
# Count non-null values in "Courses" and "Discount" columns
df2 = df.select(pl.count("Courses", "Discount"))
print("Count of Non-Null Values in Selected Columns:\n", df2)
# Output:
# Count of Non-Null Values in Selected Columns:
# shape: (1, 2)
┌─────────┬──────────┐
│ Courses ┆ Discount │
│ --- ┆ --- │
│ u32 ┆ u32 │
╞═════════╪══════════╡
│ 5 ┆ 4 │
└─────────┴──────────┘
Here,
- The
"Courses"column contains 5 non-null values, withNonebeing ignored. The"Discount"column has 4 non-null values. - The output is a single-row DataFrame with the counts of the specified columns.
<a id="h-count-total-rows-in-the-dataframe"></a>
Count Total Rows in the DataFrame
To count the total number of rows in a Polars DataFrame (including those with None values), you can use the df.height property.
# Get total number of rows in the DataFrame
df2= df.height
print("Total number of rows in the DataFrame:", df2)
print("Total Rows using len():", len(df))
# Output:
# Total number of rows in the DataFrame: 6
Here,
- The DataFrame has 6 rows in total.
df.heightandlen(df)both return the total number of rows.Nonevalues do not affect the row count (they are still counted).
<a id="h-count-rows-where-a-condition-is-met"></a>
Count Rows Where a Condition is Met
To count the number of rows that meet a specific condition in a Polars DataFrame, use the filter() method along with count(). This filters the DataFrame based on the condition and returns the count of matching rows.
# Count rows where "Courses Fee" is greater than 23000
df2 = df.filter(pl.col("Courses Fee") > 23000).height
print("Number of rows where 'Courses Fee' is greater than 23000:", df2)
# Output:
# Number of rows where 'Courses Fee' is greater than 23000: 3
Here,
pl.col("Courses Fee") > 23000Filters rows where the"Courses Fee"column is greater than23000.df.filter(...)retains only the rows that meet the specified condition.heightreturns the count of rows remaining after applying the filter.
<a id="h-conclusion"></a>
Conclusion
In conclusion, the Polars DataFrame count() function is a powerful tool for counting non-null values across columns. Additionally, you can use height to count total rows, and filter().height to count rows based on conditions.
Happy Learning!!
<a id="h-related-articles"></a>
Related Articles
- Polars DataFrame median() Usage & Examples
- Polars DataFrame std() – Usage & Examples
- Polars DataFrame tail() – Usage & Examples
- Polars DataFrame limit() Method
- How to Transpose DataFrame
- Add New Columns to Polars DataFrame
- Polars DataFrame update() – Usage & Examples
- How to Convert String to Date or Datetime in Polars
- Polars.DataFrame.mean() – Explained by Examples
<a id="h-references"></a>
