简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM