[Python] Enumerate each row for each id [duplicate]

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

  1. Stack

    Stack Membro Participativo

    This is my dataframe:

    id url
    25 google.com/main
    25 google.com/buy
    25 google.com/videos
    144 google.com/buy
    144 google.com/videos
    144 google.com/pictures
    144 google.com/maps
    992 google.com/main
    992 google.com/buy


    I need to create a new column "row_number" and enumearate each id. I want this:

    id url row_number
    25 google.com/main 1
    25 google.com/buy 2
    25 google.com/videos 3
    144 google.com/buy 1
    144 google.com/videos 2
    144 google.com/pictures 3
    144 google.com/maps 4
    992 google.com/main 1
    992 google.com/buy 2


    i was trying:

    df['row_number'] = df.groupby('id').apply(lambda x: list(range(1, len(x)+1))).explode()


    but it writes an error:

    ValueError: cannot reindex on an axis with duplicate labels

    Continue reading...

Compartilhe esta Página