how to perform columnwise count for non-zero numbers in every column in polars
- User
how to perform columnwise count for non-zero numbers in every column in polars
Assistant
To perform a column-wise count of non-zero numbers in every column using Polars, you can use the
selectmethod along with thecountexpression and a condition to filter out zero values. Here's how you can do it:import polars as pl # Example DataFrame df = pl.DataFrame({ 'A': [1, 0, 3, 0], 'B': [0, 2, 0, 4], 'C': [5, 6, 0, 7] }) # Column-wise count of non-zero numbers result = df.select([ pl.count(pl.col(name).ne(0)).alias(f"{name}_non_zero_count") for name in df.columns ]) print(result)Explanation:
pl.col(name).ne(0): This creates a boolean mask whereTrueindicates a non-zero value in the column.pl.count(...): Counts the number ofTruevalues (i.e., non-zero values) in each column.alias(f"{name}_non_zero_count"): Renames the resulting count column to include the original column name.df.select(...): Selects the computed counts for all columns.
Output:
For the example DataFrame, the output will be:
A_non_zero_count B_non_zero_count C_non_zero_count ----------------- ---------------- ---------------- 2 2 3This shows the count of non-zero values in each column (
A,B, andC).
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.