Код: Выделить всё
import pandas as pd
df = pd.DataFrame({"ref": [-1, 2, 8], "v1": [-1, 5, 0], "v2": [-1, 5, 8]})
df['count'] = df.apply(lambda r: len([i for i in r if i == r[0]]) - 1, axis=1)
df = df.drop('ref', axis=1)
df
Код: Выделить всё
v1 v2 count
0 -1 -1 2
1 5 5 0
2 0 8 1
Код: Выделить всё
import polars as pl
df = pl.DataFrame({"ref": [-1, 2, 8], "v1": [-1, 5, 0], "v2": [-1, 5, 8]})
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 ... on-on-each