Код: Выделить всё
df = pl.DataFrame({'url': ['https//abc.com', 'https//abcd.com', 'https//abcd.com/aaa', 'https//abc.com/abcd']})
Код: Выделить всё
conditions_df = pl.DataFrame({'url': ['https//abc.com', 'https//abcd.com', 'https//abcd.com/aaa', 'https//abc.com/aaa'], 'category': [['a'], ['b'], ['c'], ['d']]})
url
категория
https//abc.com
['a']< /td>
https//abcd.com
['b']
https//abcd.com/aaa
['b'] — этот начинается с https//abcd.com, это первое совпадение
https//abc.com/abcd
['a'] — это начинается с https//abc.com, это первый match
текущий код, который работает, выглядит так,
Код: Выделить всё
def add_category_column(df: pl.DataFrame, conditions_df) -> pl.DataFrame:
# Initialize the category column with empty lists
df = df.with_columns(pl.Series("category", [[] for _ in range(len(df))], dtype=pl.List(pl.String)))
# Apply the conditions to populate the category column
for row in conditions_df.iter_rows():
url_start, category = row
df = df.with_columns(
pl.when(
(pl.col("url").str.starts_with(url_start)) & (pl.col("category").list.len() == 0)
)
.then(pl.lit(category))
.otherwise(pl.col("category"))
.alias("category")
)
return df
Подробнее здесь: https://stackoverflow.com/questions/791 ... -in-polars
Мобильная версия