Check if all values are positive in a moving window

Viewed 56

I have a data frame contains a column with some values. Let be 2 a window length, I need a new column which is 1 if all elements in a rolling window are positive, 0 otherwise.

Namely:

┌─────┬─────────────┐
│ col ┆ is_positive │
│ --- ┆ ---         │
│ i64 ┆ i64         │
╞═════╪═════════════╡
│ 1   ┆ null        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ -1  ┆ 0           │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 0           │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ -1  ┆ 0           │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 0           │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 1           │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ -1  ┆ 0           │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 0           │
└─────┴─────────────┘

Any advice?

Thanks

1 Answers

One easy approach is to test the value of a rolling_min.

(
    df
    .with_column(
        (pl.col('col').rolling_min(window_size=2) > 0).alias('is_positive')
    )
)
shape: (8, 2)
┌─────┬─────────────┐
│ col ┆ is_positive │
│ --- ┆ ---         │
│ i64 ┆ bool        │
╞═════╪═════════════╡
│ 1   ┆ null        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ -1  ┆ false       │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ false       │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ -1  ┆ false       │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ false       │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ true        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ -1  ┆ false       │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ false       │
└─────┴─────────────┘

Edit

I just noticed that you specifically stated that you need 1's and 0's. We can simply add a cast to accomplish that.

(
    df
    .with_column(
        (pl.col('col').rolling_min(window_size=2) > 0).cast(pl.Int64).alias('is_positive')
    )
)
shape: (8, 2)
┌─────┬─────────────┐
│ col ┆ is_positive │
│ --- ┆ ---         │
│ i64 ┆ i64         │
╞═════╪═════════════╡
│ 1   ┆ null        │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ -1  ┆ 0           │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 0           │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ -1  ┆ 0           │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 0           │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 1           │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ -1  ┆ 0           │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1   ┆ 0           │
└─────┴─────────────┘
Related