Count positive and negative values on the rows
I have a df as follows:
import polars as pl
data_frame = pl.from_repr("""
┌──────┬──────┬──────┬──────┐
│ col0 ┆ col1 ┆ col2 ┆ col3 │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 ┆ i64 │
╞══════╪══════╪══════╪══════╡
│ 1 ┆ 1 ┆ -1 ┆ 1 │
│ -1 ┆ 1 ┆ -1 ┆ -1 │
│ 1 ┆ 1 ┆ -1 ┆ -1 │
│ -1 ┆ 1 ┆ -1 ┆ 1 │
│ 1 ┆ 1 ┆ -1 ┆ 1 │
└──────┴──────┴──────┴──────┘
""")
I need to count 1 and -1 values over the rows.
Namely, I need a new df (or new columns in the old one):
shape: (5, 2)
┌─────┬─────┐
│ pos ┆ neg │
│ --- ┆ --- │
│ u32 ┆ u32 │
╞═════╪═════╡
│ 3 ┆ 1 │
│ 1 ┆ 3 │
│ 2 ┆ 2 │
│ 2 ┆ 2 │
│ 3 ┆ 1 │
└─────┴─────┘
I solved with an example from the user guide but I don't understand how it works:
data_frame.select(
pl.fold(acc=pl.lit(0), function=lambda acc, x: acc + x, exprs=pl.col("*") > 0).alias("sum")
)
# shape: (5, 1)
# ┌─────┐
# │ pos │
# │ --- │
# │ i32 │
# ╞═════╡
# │ 3 │
# │ 1 │
# │ 2 │
# │ 2 │
# │ 3 │
# └─────┘