I have the following dataframe
JavaScript
x
9
1
df =
2
patient_id code
3
1 A
4
1 B
5
1 C
6
2 A
7
2 B
8
3 A
9
I would like to pivot it to get the following:
JavaScript
1
5
1
patient_id code_1 code_2 code_3
2
1 A B C
3
2 A B NA
4
3 A NA NA
5
Advertisement
Answer
JavaScript
1
4
1
df['col'] = df.groupby(['patient_id']).cumcount()+1
2
df.pivot(index='patient_id', columns='col' ).add_prefix('code ').reset_index()
3
4
JavaScript
1
6
1
patient_id code code
2
col code 1 code 2 code 3
3
0 1 A B C
4
1 2 A B NaN
5
2 3 A NaN NaN
6