markfairbanks / tidypolars

Tidy interface to polars
http://tidypolars.readthedocs.io
MIT License
337 stars 11 forks source link

mutate with case when expressions that have & and | #223

Closed kgilpas closed 1 year ago

kgilpas commented 1 year ago

I have code that creates a new variable with a case_when statement that has & expression like so df.mutate(t = tp.case_when(col('var1') > 0 & col('var2')==0).then(1).otherwise(-1)) and I recevied an error that said ValueError: Since Expr are lazy, the truthiness of an Expr is ambigupus. Hint: use '&' or '|' to chain Expr together, not and/or

I believe am using & so not sure what may be the issue? Thank you

markfairbanks commented 1 year ago

Not sure if you solved this already - in python you need to wrap multiple conditions in () for them to evaluate correctly:

import tidypolars as tp
from tidypolars import col

df = tp.Tibble(var1 = range(3), var2 = range(3))

df.mutate(t = tp.case_when((col('var1') == 0) & (col('var2') == 0))
              .then(1)
              .otherwise(-1))
┌──────┬──────┬─────┐
│ var1 ┆ var2 ┆ t   │
│ ---  ┆ ---  ┆ --- │
│ i64  ┆ i64  ┆ i32 │
╞══════╪══════╪═════╡
│ 0    ┆ 0    ┆ 1   │
├╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌┤
│ 1    ┆ 1    ┆ -1  │
├╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌┤
│ 2    ┆ 2    ┆ -1  │
└──────┴──────┴─────┘