[Python] How to stack multiple columns while keeping the first two columns unchanged

Discussão em 'Python' iniciado por Stack, Janeiro 23, 2025.

  1. Stack

    Stack Membro Participativo

    Python 3.11.5

    I have a df that looks like this. There are id numbers, a range of dates that is the same for each id number, and a bunch of columns with values that correspond to the individual ids in column 1.

    id date 1 2 3
    1 1/1/00 200 300
    1 1/2/00 100 200 300
    1 1/3/00 200 300
    2 1/1/00 200 300
    2 1/2/00 100 200 300
    2 1/3/00 200 300
    3 1/1/00 200 300
    3 1/2/00 100 200 300
    3 1/3/00 200 300

    What I'd like is something like this where all the columns other than the id and date column are collapsed into one, matching up the values with the correct id in column 1.

    id date value
    1 1/1/00
    1 1/2/00 100
    1 1/3/00
    2 1/1/00 200
    2 1/2/00 200
    2 1/3/00 200
    3 1/1/00 300
    3 1/2/00 300
    3 1/3/00 300

    I have tried something like the line below using stack(), but that didn't work. I thought melt() might work, but I don't know how I'd do it with the numbered column names (there are many more columns than this. Any help is appreciated.

    df = df.set_index(['homeid', 'date']).stack().reset_index()

    Continue reading...

Compartilhe esta Página