I am a beginner at Python and Pandas. I have trouble putting words to my problem, so instead, here is a sample of my dataframe (there are more values and more columns as well):
Reason Grade
'course' 15
'home' 10
'reputation' 12
'other' 16
'other' 9
'home' 14
'reputation' 10
'reputation' 8
'course' 20
'home' 19
'course' 12
'other' 10
'home' 17
'reputation' 18
And, I will like to get this:
course home reputation other
15 10 12 16
20 14 10 9
12 19 8 10
17 18
Use GroupBy.cumcount
for counter by Reason
column with DataFrame.assign
for new column and last use DataFrame.pivot
- for not exist values are added missing values:
df = df.assign(count = df.groupby('Reason').cumcount()).pivot('count','Reason','Grade')
print (df)
Reason 'course' 'home' 'other' 'reputation'
count
0 15.0 10.0 16.0 12.0
1 20.0 14.0 9.0 10.0
2 12.0 19.0 10.0 8.0
3 NaN 17.0 NaN 18.0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.