0

I want to strip a dataframe based on its data type per column. If it is a string column, a strip should be executed. If it is not a string column, it should not be striped. In pandas there is the following approach for this task:

df_clean = df_select.copy()
    for col in df_select.columns:
        if df_select[col].dtype == 'object':
            df_clean[col] = df_select[col].str.strip()

How can this be executed in polars?

import polars as pl
    
df = pl.DataFrame(
        {
            "ID": [1, 1, 1, 1,],
            "A": ["foo ", "ham", "spam ", "egg",],
            "L": ["A54", " A12", "B84", " C12"],
        }
)
4
  • pl.col(pl.Utf8).str.strip() - stackoverflow.com/questions/72359181/… Commented Feb 9, 2023 at 9:51
  • the strip is not the problem. What if I have an other datatyope than string? I need to have an exception like in the example above wit 'object' Commented Feb 9, 2023 at 9:57
  • 3
    pl.col(pl.Utf8) selects only string columns Commented Feb 9, 2023 at 9:58
  • but when I select only the string columns I need to append them again to the orignial df because I also need the none string columns. Commented Feb 9, 2023 at 10:04

1 Answer 1

3

You don't need a copy, you can directly use with_columns on df_select:

import polars as pl
    
df_select = pl.DataFrame(
        {
            "ID": [1, 1, 1, 1,],
            "A": ["foo ", "ham", "spam ", "egg",],
            "L": ["A54", " A12", "B84", " C12"],
        }
)

df_clean = df_select.with_columns(pl.col(pl.Utf8).str.strip())

Output:

shape: (4, 3)
┌─────┬──────┬─────┐
│ ID  ┆ A    ┆ L   │
│ --- ┆ ---  ┆ --- │
│ i64 ┆ str  ┆ str │
╞═════╪══════╪═════╡
│ 1   ┆ foo  ┆ A54 │
│ 1   ┆ ham  ┆ A12 │
│ 1   ┆ spam ┆ B84 │
│ 1   ┆ egg  ┆ C12 │
└─────┴──────┴─────┘
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.