Search code examples
pandasdataframestackconcatenation

Pandas: Take Every n Columns and Stack


Given this dataframe:

 pd.DataFrame([range(6),range(6,12)],columns=['A1','A2','A3','B1','B2','B3'])

    A1  A2  A3  B1  B2  B3
0   0   1   2   3   4   5
1   6   7   8   9   10  11

I want to take every n columns, 3 in this example, and stack to look like this:

       T0   T1  T2
0   A  0    1   2
    B  3    4   5
1   A  6    7   8
    B  9    10  11

I've tried many different pandas methods such as concat, stack, melt, wide_to_long and just can't stumble onto the right code after hours of experimentation.


Solution

  • Do wide_to_long + unstack and stack

    df=pd.wide_to_long(df.reset_index(),['A','B'],i='index',j='lvl').stack().unstack(1)
    lvl      1   2   3
    index             
    0     A  0   1   2
          B  3   4   5
    1     A  6   7   8
          B  9  10  11