Чтобы выполнить поиск по нескольким столбцам и создать новый столбец с флагом, если строка найдена, работает следующий код, но есть ли какой-нибудь компактный способ внутри with_columns() добиться того же?
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 │
└────────┴─────────┴────────┴─────────┴──────────────┘
Подробнее здесь: https://stackoverflow.com/questions/792 ... of-flag-if