Skip to content

[Bug]: Migration of pl.when chaining expressions #2150

@jesusestevez

Description

@jesusestevez

Describe the bug

It seems that when trying to chain multiple expressions, Narwhals is not detecting the second one and is raising an error.

This becomes clearer when trying to chain multiple when expressions.

Steps or code to reproduce the bug

pl_df = pl.DataFrame({"foo": [1, 3, 4]})

df = nw.from_native(pl_df)
df.with_columns(
    nw.when(pl.col("foo") > 2)
    .then(1)
    .when(pl.col("foo") == 1)
    .then(0)
    .otherwise(-1)
    .alias("val")
)

>>> AttributeError: 'Then' object has no attribute 'when'

Expected results

Multiple when expressions can be chained, similar as polars:

pl_df = pl.DataFrame({"foo": [1, 3, 4]})

df = nw.from_native(pl_df)
pl_df.with_columns(
    pl.when(pl.col("foo") > 2)
    .then(1)
    .when(pl.col("foo") == 1)
    .then(0)
    .otherwise(-1)
    .alias("val")
)

shape: (3, 2)
┌─────┬─────┐
│ fooval │
│ ------ │
│ i64i32 │
╞═════╪═════╡
│ 10   │
│ 31   │
│ 41   │
└─────┴─────┘

Actual results

AttributeError: 'Then' object has no attribute 'when'

Please run narwhals.show_version() and enter the output below.

System:
    python: 3.12.3 | packaged by conda-forge | (main, Apr 15 2024, 18:20:11) [MSC v.1938 64 bit (AMD64)]
executable: c:\Mambaforge\envs\myenv\python.exe
   machine: Windows-11-10.0.22621-SP0

Python dependencies:
     narwhals: 1.26.0
       pandas: 2.2.2
       polars: 1.22.0
         cudf: 
        modin: 
      pyarrow: 16.1.0
        numpy: 1.26.4

Relevant log output

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions