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

Pandas Dataframe converting to pivot table

I have a dataframe like below. I want to convert it to pivot table format, where there is each row for unique ID, new column for each Score with Type prefix.

I have about 15 different Types in the actual dataframe.

df = pd.DataFrame({'ID' : [1,1,2,2,3,3,4,4],
                   'Type':['A','B','A','B','A','B','A','B'],
                   'Score':[0.3,np.nan, 0.2, 0.1, 1.1,np.nan, 2, np.nan]})

Desired output

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

ID A_Score B_Score
1 0.3
2 0.2 0.1
3 1.1
4 2

I tried below and it almost does what I need but I need the column renames and need it in pandas dataframe

df2 = df.pivot_table(index=['ID'], columns='Type')

enter image description here

>Solution :

You can do

out = df.pivot_table(index='ID', columns='Type',values='Score').add_prefix('Score_').reset_index()
Out[355]: 
Type  ID  Score_A  Score_B
0      1      0.3      NaN
1      2      0.2      0.1
2      3      1.1      NaN
3      4      2.0      NaN
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