Format percentage in python

Asked

Viewed 1,603 times

8

How should I format the percentage for this example?

import pandas as pd
flights = pd.read_csv('data/flights_until_june.csv', sep=',')
sum_null = flights.isnull().sum()
sum_null.sort_values(ascending=False, inplace=True)
total = flights.shape[0]
percentage = round(sum_null/total * 100, 2)
print(percentage)
print('{:2%}'.format(percentage))
  • Hello Ricardo, welcome to the Stack Overflow community in English! I believe the formatting you want is to show the percentage to two decimal places with the '%' sign at the end?

  • Yes that’s what it is

1 answer

0

Just use the modifier .xf to define how many decimal places you want, in which case just replace the letter x by an integer. Note that doing so will not truncate the number, but rather round it. Already the percent symbol has to be placed after the lock keys } at the end of the "place Holder" of the number.

Example:

>>> print('{0:.2f}%'.format(34.56634))
34.57%

Note that in '{0:.2f}%' the 0 can be omitted by staying only '{:.2f}%'

Browser other questions tagged

You are not signed in. Login or sign up in order to post.