user308827 user308827 - 3 months ago 7
Python Question

Convert python pandas rows to columns

Decade difference (kg) Version
0 1510 - 1500 -0.346051 v1.0h
1 1510 - 1500 -3.553251 A2011
2 1520 - 1510 -0.356409 v1.0h
3 1520 - 1510 -2.797978 A2011
4 1530 - 1520 -0.358922 v1.0h


I want to transform the pandas dataframe such that the 2 unique enteries in the
Version
column are transfered to become columns. How do I do that?

The resulting dataframe should not have a multiindex

Answer
In [28]: df.pivot(index='Decade', columns='Version', values='difference (kg)')
Out[28]: 
Version         A2011     v1.0h
Decade                         
1510 - 1500 -3.553251 -0.346051
1520 - 1510 -2.797978 -0.356409
1530 - 1520       NaN -0.358922

or

In [31]: df.pivot(index='difference (kg)', columns='Version', values='Decade')
Out[31]: 
Version                A2011        v1.0h
difference (kg)                          
-3.553251        1510 - 1500         None
-2.797978        1520 - 1510         None
-0.358922               None  1530 - 1520
-0.356409               None  1520 - 1510
-0.346051               None  1510 - 1500

both satisfy your requirements.

Comments