Question

Is there a simple way in pandas to reshape the following data frame:

df = pd.DataFrame({'n':[1,1,2,2,1,1,2,2],
                   'l':['a','b','a','b','a','b','a','b'],
                   'v':[12,43,55,19,23,52,61,39],
                   'g':[0,0,0,0,1,1,1,1]
                  })

to this format?:

   g  a1 b1 a2 b2
   0  12 43 55 19
   1  23 52 61 39
Was it helpful?

Solution

In [75]: df['ln'] = df['l'] + df['n'].astype(str)

In [76]: df.set_index(['g', 'ln'])['v'].unstack('ln')
Out[76]: 
ln  a1  a2  b1  b2
g                 
0   12  55  43  19
1   23  61  52  39

[2 rows x 4 columns]

If you need that ordering then:

In [77]: df.set_index(['g', 'ln'])['v'].unstack('ln')[['a1', 'b1', 'a2', 'b2']]
Out[77]: 
ln  a1  b1  a2  b2
g                 
0   12  43  55  19
1   23  52  61  39

[2 rows x 4 columns]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top