Skip to content
Advertisement

Python: Pivot dataframe to introduce new columns

I have the following dataframe

df = 
patient_id code
1          A
1          B
1          C
2          A
2          B
3          A

I would like to pivot it to get the following:

patient_id code_1 code_2 code_3
1          A      B      C
2          A      B      NA
3          A      NA     NA

Advertisement

Answer

df['col'] = df.groupby(['patient_id']).cumcount()+1
df.pivot(index='patient_id', columns='col' ).add_prefix('code ').reset_index()

    patient_id  code code
col             code 1  code 2  code 3
0         1          A       B       C
1         2          A       B     NaN
2         3          A     NaN     NaN
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement