Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I transpose a dataframe after groupby?

I have this table

port valueA valueB valueC
1 3.1 58.2 0.09
2 3.09 58.3 0.1
3 3.09 58.15 0.09
4 3.11 58.2 0.1
1 3.1 58.25 0.09
2 3.1 58.25 0.09
3 3.08 58.15 0.09
4 3.09 58.1 0.09

I would like to group based on ‘port’ and then have them as columns in a new dataframe that has valueA as rows, like this:

1 2 3 4
3.1 3.09 3.09 3.11
3.1 3.1 3.08 3.09

How do I do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Example

import pandas as pd
data1 = {'port': [1, 2, 3, 4, 1, 2, 3, 4], 
         'valueA': [3.1, 3.09, 3.09, 3.11, 3.1, 3.1, 3.08, 3.09], 
         'valueB': [58.2, 58.3, 58.15, 58.2, 58.25, 58.25, 58.15, 58.1], 
         'valueC': [0.09, 0.1, 0.09, 0.1, 0.09, 0.09, 0.09, 0.09]}
df = pd.DataFrame(data1)

Code

grp = df.groupby('port').cumcount()
df.set_index([grp, 'port'])['valueA'].unstack().rename_axis('', axis=1)

output:

    1       2       3       4
0   3.1     3.09    3.09    3.11
1   3.1     3.10    3.08    3.09

Intermediate

df & grp:

df                                      grp
    port    valueA  valueB  valueC      
0   1       3.10    58.20   0.09        0
1   2       3.09    58.30   0.10        0
2   3       3.09    58.15   0.09        0
3   4       3.11    58.20   0.10        0
4   1       3.10    58.25   0.09        1
5   2       3.10    58.25   0.09        1
6   3       3.08    58.15   0.09        1
7   4       3.09    58.10   0.09        1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading