Search code examples
python-polars

Python Polars getting ColumnNotFound when use the when() method


I'm trying to use a combination of contains method together when in polars. However, I'm getting the following annoying error:

Exception has occurred: ColumnNotFoundError
Foo message.

I read the documentation, but the examples are quite simple and don't cover a situation like this. Here follows my code sample:

df = df.with_columns(
    pl.when(pl.col("Foo").str.contains("Foo message. Bar Message."))
    .then("Foo message")
    .alias("Foo_Column")
)

Any help is appreciated.


Solution

  • You're probably looking for

    df = df.with_columns(
        pl.when(pl.col("Foo").str.contains("Foo message. Bar Message."))
        .then(pl.lit("Foo message"))
        .alias("Foo_Column")
    )
    

    otherwise Polars thinks "Foo message" is the name of a column