Peter Lucas
Peter Lucas

Reputation: 1991

Most efficient way to calculate a percentage in a dataframe then diplay as a percentage not a float

Afternoon All,

I have the results of my filtered dataframe:

df[df['state']=='Done']

2       Done
5       Done
45      Done
48      Done
74      Done
93      Done

I would like to calculate the total percentage of done trades compared to the total number of records in the original dataframe:

done_trades = df[df['state']=='Done']['state'].count()
total_trades = df['state'].count()
RFQ_Hit_Rate = done_trades / total_trades
display(RFQ_Hit_Rate)

0.12320675105485232

UserWarning: Boolean Series key will be reindexed to match DataFrame index. after removing the cwd from sys.path.

Based on the error outputted this is not the ideal solution, I assume because the .count function returns a vector and not a number .

Any recommendations on how this can be achieved more efficiently? The formattting of 0.12320675105485232 to percentage? I was going to use .map('{:,.2f}'.format) but this failed.

Peter

Upvotes: 1

Views: 74

Answers (1)

Alex Lee
Alex Lee

Reputation: 339

About formatting, I have a easy way maybe not the best, you can change the precision by adjusting the parameter of round:

number  = 0.12320675105485232

number = round(number * 100, 2)
print("{}%".format(number))

Output:

12.32%

Upvotes: 1

Related Questions