如何将字符串列编码为极坐标上的整数?

问题描述 投票:0回答:1

我想以简单的方式将给定列的值(例如字符串)“编码”为任意整数标识符?

df = (
    pl.DataFrame({"animal": ['elephant', 'dog', 'cat', 'mouse'],
    "country": ['Mexico', 'Denmark', 'Mexico', 'France'], 
    "cost": [1000.0, 20.0, 10.0, 120.0]})
)
print(df)
shape: (4, 3)
┌──────────┬─────────┬────────┐
│ animal   ┆ country ┆ cost   │
│ ---      ┆ ---     ┆ ---    │
│ str      ┆ str     ┆ f64    │
╞══════════╪═════════╪════════╡
│ elephant ┆ Mexico  ┆ 1000.0 │
│ dog      ┆ Denmark ┆ 20.0   │
│ cat      ┆ Mexico  ┆ 10.0   │
│ mouse    ┆ France  ┆ 120.0  │
└──────────┴─────────┴────────┘

我想对

animal
country
列进行编码以获得类似的内容

shape: (4, 5)
┌──────────┬─────────┬────────┬────────────────┬─────────────────┐
│ animal   ┆ country ┆ cost   ┆ animal_encoded ┆ country_encoded │
│ ---      ┆ ---     ┆ ---    ┆ ---            ┆ ---             │
│ str      ┆ str     ┆ f64    ┆ i64            ┆ i64             │
╞══════════╪═════════╪════════╪════════════════╪═════════════════╡
│ elephant ┆ Mexico  ┆ 1000.0 ┆ 0              ┆ 0               │
│ dog      ┆ Denmark ┆ 20.0   ┆ 1              ┆ 1               │
│ cat      ┆ Mexico  ┆ 10.0   ┆ 2              ┆ 0               │
│ mouse    ┆ France  ┆ 120.0  ┆ 3              ┆ 2               │
└──────────┴─────────┴────────┴────────────────┴─────────────────┘

我认为从

unique
d 上下文中进行某种行索引,然后
over
扩展到相同数量的原始行可以解决问题,但我无法实现它。

python-polars
1个回答
2
投票

我想我已经找到了一个解决方案,基于这个问题的答案。

df = (
    pl.DataFrame({
    "animal": ['elephant', 'dog', 'cat', 'mouse'], 
    "country": ['Mexico', 'Denmark', 'Mexico', 'France'], 
    "cost": [1000.0, 20.0, 10.0, 120.0]})
)

(
     df
    .with_columns(
    pl.col(i).rank('dense').cast(pl.Int64).name.suffix('_encoded') for i in ['animal', 'country']
    )

)

shape: (4, 5)
┌──────────┬─────────┬────────┬────────────────┬─────────────────┐
│ animal   ┆ country ┆ cost   ┆ animal_encoded ┆ country_encoded │
│ ---      ┆ ---     ┆ ---    ┆ ---            ┆ ---             │
│ str      ┆ str     ┆ f64    ┆ i64            ┆ i64             │
╞══════════╪═════════╪════════╪════════════════╪═════════════════╡
│ elephant ┆ Mexico  ┆ 1000.0 ┆ 3              ┆ 3               │
│ dog      ┆ Denmark ┆ 20.0   ┆ 2              ┆ 1               │
│ cat      ┆ Mexico  ┆ 10.0   ┆ 1              ┆ 3               │
│ mouse    ┆ France  ┆ 120.0  ┆ 4              ┆ 2               │
└──────────┴─────────┴────────┴────────────────┴─────────────────┘


© www.soinside.com 2019 - 2024. All rights reserved.