Search code examples
strippython-polars

strip entire polars dataframe


I want to strip leading and trailing whitespaces from a polars dataframe with this line of code:

df = pl.DataFrame(
    {
        "A": ["foo ", "ham", "spam ", "egg",],
        "L": ["A54", " A12", "B84", " C12"],

    }
)
print(df)

shape: (4, 2)
┌───────┬──────┐
│ A     ┆ L    │
│ ---   ┆ ---  │
│ str   ┆ str  │
╞═══════╪══════╡
│ foo   ┆ A54  │
│ ham   ┆  A12 │
│ spam  ┆ B84  │
│ egg   ┆  C12 │
└───────┴──────┘

df_clean = df.select(
            [pl.all().map(lambda x: x.strip() if isinstance(x, str) else x)]
        )

But it did not work. How can I strip an entire polars dataframe?


Solution

  • .str.strip() is deprecated now.

    .str.strip_chars() should be used instead.