Skip to content Skip to sidebar Skip to footer

How To Split Columns And Merge Them As Rows?

I have a data frame as follows: ID Date ColA1 ColB1 ColA2 ColB2 ColA3 ColB3 id1 date1 1 2 3 4 5 6 id2 date2 7 8

Solution 1:

you need wide_to_long

pd.wide_to_long(df.reset_index(), stubnames = ['ColA', 'ColB'], i ='index', j ='value').reset_index(drop=True)

    ColA    ColB
012178234391045651112

Edit Output without reset_index()

pd.wide_to_long(df.reset_index(), stubnames = ['ColA', 'ColB'], i = 'index', j = 'value')
            ColA    ColB
index   value       
011211780234129100356131112

Edit2 With the new data sample provide by OP:

pd.wide_to_long(df, stubnames = ['ColA', 'ColB'], i = ['ID', 'Date'], j = 'value').reset_index([0,1])

    ID  Date    ColA    ColB
value               
1   id1 date1   1   2
2   id1 date1   3   4
3   id1 date1   5   6
1   id2 date2   7   8
2   id2 date2   9   10
3   id2 date2   11  12

Post a Comment for "How To Split Columns And Merge Them As Rows?"