Код: Выделить всё
import polars as pl
df = pl.DataFrame({"pop_1": ["100","0021"],"pop_2":["11002","0000",]})
Код: Выделить всё
shape: (2, 2)
┌───────┬───────┐
│ pop_1 ┆ pop_2 │
│ --- ┆ --- │
│ str ┆ str │
╞═══════╪═══════╡
│ 100 ┆ 11002 │
│ 0021 ┆ 0000 │
└───────┴───────┘
col_2 row1 имеет 8 отличий сама с собой;
col_1 и col_2 имеют 9 различий между собой в строке 1.
Наивная реализация этого будет такой:
Код: Выделить всё
def get_dxy(str1,str2):
diffs = 0
for x in str1:
for y in str2:
if x!=y:
diffs+=1
return diffs
def get_pi(str1):
diffs = 0
for i in range(len(str1)-1):
for j in range(i+1,len(str1)):
if str1[i]!=str1[j]:
diffs+=1
return diffs
Код: Выделить всё
df = df.with_columns( pl.col('pop_1')
.map_elements(get_pi, return_dtype=pl.Int64)
.alias('pi_1')
)
df = df.with_columns( pl.col('pop_2')
.map_elements(get_pi, return_dtype=pl.Int64)
.alias('pi_2')
)
df = df.with_columns(
pl.struct("pop_1", "pop_2")
.map_elements(lambda cols: get_dxy(cols["pop_1"], cols["pop_2"]), return_dtype=pl.Int64)
.alias("dxy")
)
df
Код: Выделить всё
shape: (2, 5)
┌───────┬───────┬──────┬──────┬─────┐
│ pop_1 ┆ pop_2 ┆ pi_1 ┆ pi_2 ┆ dxy │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 ┆ i64 ┆ i64 │
╞═══════╪═══════╪══════╪══════╪═════╡
│ 100 ┆ 11002 ┆ 2 ┆ 8 ┆ 9 │
│ 0021 ┆ 0000 ┆ 5 ┆ 0 ┆ 8 │
└───────┴───────┴──────┴──────┴─────┘
Могу ли я получить несколько советов, как это сделать?
Подробнее здесь: https://stackoverflow.com/questions/790 ... -in-polars
Мобильная версия