Home > Enterprise >  Python: Pivot dataframe to introduce new columns
Python: Pivot dataframe to introduce new columns

Time:07-27

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

CodePudding user response:

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

CodePudding user response:

You can pivot calling 'code' twice:

df.pivot('patient_id', 'code', 'code')

Which gives

code        A    B    C
patient_id
1           A    B    C
2           A    B  NaN
3           A  NaN  NaN

Then just rename your columns.

  • Related