[英]Python: Pivot dataframe to introduce new columns
I have the following dataframe我有以下 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:我想 pivot 它得到以下:
patient_id code_1 code_2 code_3
1 A B C
2 A B NA
3 A NA NA
You can pivot
calling 'code'
twice:您可以
pivot
调用'code'
两次:
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.然后只需重命名您的列。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.