Format certain floating dataframe columns into percentage in pandas Format certain floating dataframe columns into percentage in pandas python python

Format certain floating dataframe columns into percentage in pandas


The accepted answer suggests to modify the raw data for presentation purposes, something you generally do not want. Imagine you need to make further analyses with these columns and you need the precision you lost with rounding.

You can modify the formatting of individual columns in data frames, in your case:

output = df.to_string(formatters={    'var1': '{:,.2f}'.format,    'var2': '{:,.2f}'.format,    'var3': '{:,.2%}'.format})print(output)

For your information '{:,.2%}'.format(0.214) yields 21.40%, so no need for multiplying by 100.

You don't have a nice HTML table anymore but a text representation. If you need to stay with HTML use the to_html function instead.

from IPython.core.display import display, HTMLoutput = df.to_html(formatters={    'var1': '{:,.2f}'.format,    'var2': '{:,.2f}'.format,    'var3': '{:,.2%}'.format})display(HTML(output))

Update

As of pandas 0.17.1, life got easier and we can get a beautiful html table right away:

df.style.format({    'var1': '{:,.2f}'.format,    'var2': '{:,.2f}'.format,    'var3': '{:,.2%}'.format,})


You could also set the default format for float :

pd.options.display.float_format = '{:.2%}'.format

Use '{:.2%}' instead of '{:.2f}%' - The former converts 0.41 to 41.00% (correctly), the latter to 0.41% (incorrectly)


replace the values using the round function, and format the string representation of the percentage numbers:

df['var2'] = pd.Series([round(val, 2) for val in df['var2']], index = df.index)df['var3'] = pd.Series(["{0:.2f}%".format(val * 100) for val in df['var3']], index = df.index)

The round function rounds a floating point number to the number of decimal places provided as second argument to the function.

String formatting allows you to represent the numbers as you wish. You can change the number of decimal places shown by changing the number before the f.

p.s. I was not sure if your 'percentage' numbers had already been multiplied by 100. If they have then clearly you will want to change the number of decimals displayed, and remove the hundred multiplication.