[Python] Renumerate a column in a group [duplicate]

Discussão em 'Python' iniciado por Stack, Setembro 14, 2024.

  1. Stack

    Stack Membro Participativo

    I'm looking for a scalable way to re-numerate groups (in my case cluster number) in a column. Below the current state with Pandas schema.

    data = [
    ["Adam", 1, 22],
    ["Eddy", 0, 22],
    ["Boby", 9, 22],
    ["Timy", 2, 26],
    ["Carl", 9, 26],
    ["Anna", 0, 33],
    ["Paul", 5, 35],
    ["Mike", 7, 51],
    ]

    current = pd.DataFrame(data,
    columns=['name', 'score', 'cluster']
    ).astype({'name':'string', 'score':'Int64', 'cluster':'Int64'})


    current table looks like that:

    +----+--------+---------+-----------+
    | | name | score | cluster |
    |----+--------+---------+-----------|
    | 0 | Adam | 1 | 22 |
    | 1 | Eddy | 0 | 22 |
    | 2 | Boby | 9 | 22 |
    | 3 | Timy | 2 | 26 |
    | 4 | Carl | 9 | 26 |
    | 5 | Anna | 0 | 33 |
    | 6 | Paul | 5 | 35 |
    | 7 | Mike | 7 | 51 |
    +----+--------+---------+-----------+


    my desired state would be:

    +----+--------+---------+-----------+
    | | name | score | cluster |
    |----+--------+---------+-----------|
    | 0 | Adam | 1 | 1 |
    | 1 | Eddy | 0 | 1 |
    | 2 | Boby | 9 | 1 |
    | 3 | Timy | 2 | 2 |
    | 4 | Carl | 9 | 2 |
    | 5 | Anna | 0 | 3 |
    | 6 | Paul | 5 | 4 |
    | 7 | Mike | 7 | 5 |
    +----+--------+---------+-----------+


    Assume there will be milions of rows and hundreds of clusters. For a very small amount of clusters I can do it by hand but I need a scalable solution. I've tried to iterate over groups after .groupby("cluster") and to assign consecutive numbers but I failed.

    Continue reading...

Compartilhe esta Página