[Python] How to search string across multiple columns, and create a new column of flag if...

Discussão em 'Python' iniciado por Stack, Novembro 22, 2025.

  1. Stack

    Stack Membro Participativo

    To search over multiple columns, and create a new column of flag if string found, the following code works, but is there any compact way inside with_columns() to achieve the same?

    import polars as pl

    df = pl.DataFrame({
    "col1": ["hello", "world", "polars"],
    "col2": ["data", "science", "hello"],
    "col3": ["test", "string", "match"],
    "col4": ["hello", "example", "test"]
    })


    search_string = "hello"

    condition = pl.lit(False)


    for col in df.columns:
    condition |= pl.col(col).str.contains(search_string)

    df = df.with_columns(
    condition.alias("string_found") + 0
    )


    print(df)



    shape: (3, 5)
    ┌────────┬─────────┬────────┬─────────┬──────────────┐
    │ col1 ┆ col2 ┆ col3 ┆ col4 ┆ string_found │
    │ --- ┆ --- ┆ --- ┆ --- ┆ --- │
    │ str ┆ str ┆ str ┆ str ┆ i32 │
    ╞════════╪═════════╪════════╪═════════╪══════════════╡
    │ hello ┆ data ┆ test ┆ hello ┆ 1 │
    │ world ┆ science ┆ string ┆ example ┆ 0 │
    │ polars ┆ hello ┆ match ┆ test ┆ 1 │
    └────────┴─────────┴────────┴─────────┴──────────────┘

    Continue reading...

Compartilhe esta Página