Я хочу посчитать, сколько раз значение ref появляется в других столбцах для каждой строки.
Код: Выделить всё
import polars as pl
df = pl.from_repr('''
┌─────┬─────┬─────┐
│ ref ┆ v1 ┆ v2 │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ -1 ┆ -1 ┆ -1 │ # -1 appears 2 times (excluding ref)
│ 2 ┆ 5 ┆ 5 │ # 2 appears 0 times
│ 8 ┆ 0 ┆ 8 │ # 8 appears 1 time
└─────┴─────┴─────┘
''')
Код: Выделить всё
df_pd = df.to_pandas()
df_pd['count'] = df_pd.apply(lambda r: len([i for i in r if i == r[0]]) - 1, axis=1)
df_pd = df_pd.drop('ref', axis=1)
df_pd
Код: Выделить всё
v1 v2 count
0 -1 -1 2
1 5 5 0
2 0 8 1
Код: Выделить всё
x = df.map_rows(lambda r: len([i for i in r if i == r[0]]) - 1).rename({'map': 'count'})
df = df.hstack([x.to_series()]).drop('ref')
df
Код: Выделить всё
shape: (3, 3)
┌─────┬─────┬───────┐
│ v1 ┆ v2 ┆ count │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═══════╡
│ -1 ┆ -1 ┆ 2 │
│ 5 ┆ 5 ┆ 0 │
│ 0 ┆ 8 ┆ 1 │
└─────┴─────┴───────┘
Я был бы благодарен за любые улучшения в приведенном выше коде.
Подробнее здесь: https://stackoverflow.com/questions/765 ... rs-express
Мобильная версия