[Python] How to stack columns in a dataframe [duplicate]

Discussão em 'Python' iniciado por Stack, Julho 12, 2025.

  1. Stack

    Stack Membro Participativo

    I have a data frame df which looks like this:

    column_A column_B ss1 ss2 s_avg
    1 149.0 638.0 1.0 3.0 2.0
    2 149.0 638.0 3.0 9.0 6.0
    3 149.0 638.0 5.0 3.0 4.0
    4 149.0 638.0 7.0 11.0 9.0


    I need to stack two columns on top of each other and convert it to a different dataframe like this:

    column_A column_B ss type s_avg
    1 149.0 638.0 1.0 rr1 2.0
    2 149.0 638.0 3.0 rr1 6.0
    3 149.0 638.0 5.0 rr1 4.0
    4 149.0 638.0 7.0 rr1 9.0
    5 149.0 638.0 3.0 rr2 2.0
    6 149.0 638.0 9.0 rr2 6.0
    7 149.0 638.0 3.0 rr2 4.0
    8 149.0 638.0 11.0 rr2 9.0


    Basically some columns should be left untouched (column_A, column_B, s_avg), just duplicated while others (ss1, ss2) need to be categorized without loss of data.

    I know we can iterate thru each row and keep on appending it to a new dataframe. Any easy way to do this by just passing a mapping dictionary for column to type field eg: {'ss1':'rr1', 'ss2':'rr2'} and new_colname='ss'

    It's also ok if I am at least able to achieve the type column with actual column names like this below:

    column_A column_B ss type s_avg
    1 149.0 638.0 1.0 ss1 2.0
    2 149.0 638.0 3.0 ss1 6.0
    3 149.0 638.0 5.0 ss1 4.0
    4 149.0 638.0 7.0 ss1 9.0
    5 149.0 638.0 3.0 ss2 2.0
    6 149.0 638.0 9.0 ss2 6.0
    7 149.0 638.0 3.0 ss2 4.0
    8 149.0 638.0 11.0 ss2 9.0


    The dataframe can be huge, so any easy efficient inbuilt methods are welcome.

    Continue reading...

Compartilhe esta Página