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 to melt a dataframe so repeated items become the values that correspond to the index

I have this dataframe:

df = pd.DataFrame({'Status':['CO','AD','AD','AD','OT','CO','OT','AD'],
                   'Mutation':['H157Y','R47H','R47H','R67H','R62H','D87N','D39E','D39E']})
print(df)
  
  Status Mutation
0     CO    H157Y
1     AD     R47H
2     AD     R47H
3     AD     R67H
4     OT     R62H
5     CO     D87N
6     OT     D39E
7     AD     D39E

I want the dataframe to look like this:

df2 = pd.DataFrame({'Status':['CO','AD','OT'],'H157Y':[1,0,0],'R47H':[0,2,0],'R67H':[0,1,0],
                    'R62H':[0,0,1],'D87N':[1,0,0],'D39E':[1,0,1]})
print(df2)

  Status  H157Y  R47H  R67H  R62H  D87N  D39E
0     CO      1     0     0     0     1     1
1     AD      0     2     1     0     0     0
2     OT      0     0     0     1     0     1

Where mutations are the column names and their values – the number of hits – corresponds to the status.

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 :

This should do the trick:

df.groupby(['Status', 'Mutation']).size().unstack(fill_value=0)
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