Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calculating rowwise minimum of two series?

Is there any function that can generate a series by calculating rowwise minimum of two series? This would be similar to np.minimum

>>> a = [1,4,2,5,2]
>>> b = [5,1,4,2,5]
>>> np.minimum(a,b)
[1,1,2,2,2]

Thanks.

like image 740
hakan.t Avatar asked Oct 17 '25 11:10

hakan.t


2 Answers

It's 2023 and polars has min_horizontal. Warning: It ignores None(s) but respects np.nans.

import polars as pl
import numpy as np

df = pl.DataFrame(
    {
        "a": [1, 4, 2, 5, 2],
        "b": [5, 1, 4, None, 5],
        "c": [3, 2, 5, 7, np.nan],
    }
)
df = df.with_columns(
    pl.min_horizontal(["a", "b", "c"]),
)
print(df)

yielding

shape: (5, 4)
┌─────┬──────┬─────┬─────┐
│ a   ┆ b    ┆ c   ┆ min │
│ --- ┆ ---  ┆ --- ┆ --- │
│ i64 ┆ i64  ┆ f64 ┆ f64 │
╞═════╪══════╪═════╪═════╡
│ 1   ┆ 5    ┆ 3.0 ┆ 1.0 │
│ 4   ┆ 1    ┆ 2.0 ┆ 1.0 │
│ 2   ┆ 4    ┆ 5.0 ┆ 2.0 │
│ 5   ┆ null ┆ 7.0 ┆ 5.0 │
│ 2   ┆ 5    ┆ NaN ┆ NaN │
└─────┴──────┴─────┴─────┘
like image 136
gebbissimo Avatar answered Oct 20 '25 02:10

gebbissimo


q =df.lazy().with_columns(pl.when(pl.col("a")>pl.col("b")).then(pl.col("b")).otherwise(pl.col("a")).alias("minimum"))

df = q.collect()

i didn't tested it but this should work i think

like image 34
seb2704 Avatar answered Oct 20 '25 02:10

seb2704



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!