You can perform a column-wise count of non-zero numbers in every column of a Polars DataFrame using several approaches. Here are a few common and efficient methods:
1. Using pl.col().filter() and count():
This is a straightforward and readable approach:
import polars as pl
# Sample DataFrame
data = {'col1': [1, 0, 3, 0, 5],
'col2': [0, 2, 0, 4, 0],
'col3': [6, 0, 7, 8, 0]}
df = pl.DataFrame(data)
result = df.select([
pl.col(col).filter(pl.col(col) != 0).count().alias(f"{col}_non_zero_count")
for col in df.columns
])
print(result)
Explanation:
pl.col(col): Selects each column in the DataFrame.
.filter(pl.col(col) != 0): Filters the column to keep only the non-zero elements. You can use other conditions like pl.col(col) > 0 for strictly positive counts.
.count(): Counts the number of elements remaining after the filtering.
.alias(f"{col}_non_zero_count"): Gives the resulting column a descriptive name.
df.select([...]): Applies the transformation to each column and combines the results into a new DataFrame.
2. Using pl.col().is_not_null() & pl.col() != 0 (Explicit Null Handling):
This method explicitly handles potential null values (None or pl.Null in Polars). If you have nulls in your data, this is crucial to avoid incorrect counts.
import polars as pl
data = {'col1': [1, None, 3, 0, 5],
'col2': [0, 2, None, 4, 0],
'col3': [6, 0, 7, 8, None]}
df = pl.DataFrame(data)
result = df.select([
pl.col(col).filter(pl.col(col).is_not_null() & (pl.col(col) != 0)).count().alias(f"{col}_non_zero_count")
for col in df.columns
])
print(result)
Explanation:
pl.col(col).is_not_null(): Checks if the value in the column is not null.
(pl.col(col) != 0): Checks if the value is not equal to 0.
&: The bitwise AND operator combines the two conditions. The element is kept only if it's both non-null and non-zero.
3. Using pl.when().then().otherwise() (Conditional Approach):
While slightly less concise than the filter approach, this demonstrates a conditional approach that can be useful for more complex counting scenarios.
import polars as pl
data = {'col1': [1, 0, 3, 0, 5],
'col2': [0, 2, 0, 4, 0],
'col3': [6, 0, 7, 8, 0]}
df = pl.DataFrame(data)
result = df.select([
pl.when(pl.col(col) != 0).then(1).otherwise(0).sum().alias(f"{col}_non_zero_count")
for col in df.columns
])
print(result)
Explanation:
pl.when(pl.col(col) != 0).then(1).otherwise(0): For each element in the column, this creates a new Series where non-zero values are replaced with 1 and zero values are replaced with 0.
.sum(): The sum of this Series effectively counts the number of non-zero values in the original column.
4. Optimized for large DataFrames using pl.col().sum() with Boolean Arrays:
This is usually the most performant, especially for large DataFrames, because it leverages Polars' efficient boolean operations. It avoids the explicit filtering step.
import polars as pl
data = {'col1': [1, 0, 3, 0, 5],
'col2': [0, 2, 0, 4, 0],
'col3': [6, 0, 7, 8, 0]}
df = pl.DataFrame(data)
result = df.select([
(pl.col(col) != 0).sum().alias(f"{col}_non_zero_count")
for col in df.columns
])
print(result)
Explanation:
(pl.col(col) != 0): This creates a boolean Series. True where the column value is not 0, and False where it is 0. Polars is very efficient at creating boolean series.
.sum(): In Polars (and many other data analysis libraries), True is treated as 1 and False is treated as 0 when summing. Therefore, summing the boolean Series directly counts the number of True values (i.e., the number of non-zero values).
Important Note: If you need to handle null values in addition to zeros, the boolean expression needs to be adjusted:
result = df.select([
(pl.col(col).is_not_null() & (pl.col(col) != 0)).sum().alias(f"{col}_non_zero_count")
for col in df.columns
])
Which Method to Choose:
- For readability and smaller DataFrames: The
filter() and count() approach (method 1) is a good starting point.
- When null values are present: Use the
is_not_null() check in conjunction with the zero check (method 2 or the updated version of method 4). This is essential to avoid incorrect counts.
- For best performance on large DataFrames: The boolean array summing method (method 4, with or without the
is_not_null() check, depending on your data) will generally be the fastest. Polars is highly optimized for boolean operations.
- For more complex conditions: The
pl.when().then().otherwise() (method 3) provides flexibility for counting based on more intricate logic.
Remember to consider the presence of null values in your data and choose the method that handles them correctly to ensure accurate counts. The boolean array summation approach is typically the most efficient, particularly for large datasets. Always benchmark with your specific data and hardware to confirm the optimal approach.