Menu Close

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

To display Python Pandas DataFrame of floats using a format string for columns, we use the map method.

For instance, we write

import pandas as pd
df = 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)

to create a data frame df with DataFrame.

Then we call call map on the df['cost'] column to return a string with the value interpolated to the format string with format.

Posted in Python, Python Answers