[Python] How to expand the number of dataframe rows based on column titles?

Discussão em 'Python' iniciado por Stack, Março 22, 2025.

  1. Stack

    Stack Membro Participativo

    I've got a dataframe of the form:

    name 0 1 2
    0 A 4 2 1
    1 B 2 3 4
    2 C 1 3 2


    This is the result of grouping and summarizing data earlier in my real world data process. What I would like to do now, is to expand (explode?) each row so that each element in that row fills a number of rows corresponding to the column title, except for name, so that the dataframe ends up like this:

    name 0 1 2
    ------------------
    A 0 1 2
    A 0 1 nan
    A 0 nan nan
    A 0 nan nan
    B 0 1 2
    B 0 1 2
    B nan 1 2
    B nan nan 2
    C 0 1 2
    C nan 1 2
    C nan 1 nan


    I've tried a bunch of stuff with df.iterrows() and assigning new columns to an empty dataframe with columns with the lenghts of the max of each row and filling up with nans, but it ended up buggy and really messy. It would be great if any of you pandas experts could take a look. Thank you for any suggestions!

    Reproducible dataframe


    import pandas as pd
    df = pd.DataFrame({'name': ['A','B','C'], 0:[4,2,1], 1:[2,3,3], 2:[1,4,2]})

    Continue reading...

Compartilhe esta Página