I have DataFrame that looks like this:
BIB# COURSE FINISH
0 1 COURSE 1 21.235
1 1 COURSE 2 23.345
2 1 STRAIGHT-GLIDING 20.690
3 2 COURSE 1 20.220
4 2 COURSE 2 22.535
5 2 STRAIGHT-GLIDING 19.910
Now I want to calculate a ratio score for each BIB#. The ratio score should look like this:
PERFORMANCE = COURSE 1 + COURSE 2 / STRAIGHT-GLIDING
The values for this calculation is found in the FINISH column.
I think I can create a function that loops over each row in the DataFrame but I guess there is a better way to do it using Pandas? Thanks!
(If I were to create the function, then I would loop through each BIB# with if tests)
Use DataFrame.pivot
, then add and divide columns each other:
df1 = df.pivot('BIB#','COURSE','FINISH')
df1['PERFORMANCE'] = df1['COURSE 1'].add(df1['COURSE 2']).div(df1['STRAIGHT-GLIDING'])
print (df1)
COURSE COURSE 1 COURSE 2 STRAIGHT-GLIDING PERFORMANCE
BIB#
1 21.235 23.345 20.69 2.154664
2 20.220 22.535 19.91 2.147413
If need same format like original add DataFrame.stack
with Series.reset_index
:
df2 = df1.stack().reset_index(name='FINISH')
print (df2)
BIB# COURSE FINISH
0 1 COURSE 1 21.235000
1 1 COURSE 2 23.345000
2 1 STRAIGHT-GLIDING 20.690000
3 1 PERFORMANCE 2.154664
4 2 COURSE 1 20.220000
5 2 COURSE 2 22.535000
6 2 STRAIGHT-GLIDING 19.910000
7 2 PERFORMANCE 2.147413
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments