How to display pandas DataFrame of floats using a format string for columns? How to display pandas DataFrame of floats using a format string for columns? pandas pandas

How to display pandas DataFrame of floats using a format string for columns?


import pandas as pdpd.options.display.float_format = '${:,.2f}'.formatdf = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],                  index=['foo','bar','baz','quux'],                  columns=['cost'])print(df)

yields

        costfoo  $123.46bar  $234.57baz  $345.68quux $456.79

but this only works if you want every float to be formatted with a dollar sign.

Otherwise, if you want dollar formatting for some floats only, then I think you'll have to pre-modify the dataframe (converting those floats to strings):

import pandas as pddf = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],                  index=['foo','bar','baz','quux'],                  columns=['cost'])df['foo'] = df['cost']df['cost'] = df['cost'].map('${:,.2f}'.format)print(df)

yields

         cost       foofoo   $123.46  123.4567bar   $234.57  234.5678baz   $345.68  345.6789quux  $456.79  456.7890


If you don't want to modify the dataframe, you could use a custom formatter for that column.

import pandas as pdpd.options.display.float_format = '${:,.2f}'.formatdf = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],                  index=['foo','bar','baz','quux'],                  columns=['cost'])print df.to_string(formatters={'cost':'${:,.2f}'.format})

yields

        costfoo  $123.46bar  $234.57baz  $345.68quux $456.79


As of Pandas 0.17 there is now a styling system which essentially provides formatted views of a DataFrame using Python format strings:

import pandas as pdimport numpy as npconstants = pd.DataFrame([('pi',np.pi),('e',np.e)],                   columns=['name','value'])C = constants.style.format({'name': '~~ {} ~~', 'value':'--> {:15.10f} <--'})C

which displays

enter image description here

This is a view object; the DataFrame itself does not change formatting, but updates in the DataFrame are reflected in the view:

constants.name = ['pie','eek']C

enter image description here

However it appears to have some limitations:

  • Adding new rows and/or columns in-place seems to cause inconsistency in the styled view (doesn't add row/column labels):

    constants.loc[2] = dict(name='bogus', value=123.456)constants['comment'] = ['fee','fie','fo']constants

enter image description here

which looks ok but:

C

enter image description here

  • Formatting works only for values, not index entries:

    constants = pd.DataFrame([('pi',np.pi),('e',np.e)],               columns=['name','value'])constants.set_index('name',inplace=True)C = constants.style.format({'name': '~~ {} ~~', 'value':'--> {:15.10f} <--'})C

enter image description here