Explain Codes LogoExplain Codes Logo

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

python
pandas
dataframe
formatting
Nikita BarsukovbyNikita Barsukov·Aug 3, 2024
TLDR

Consider using DataFrame.style.format with a dictionary. It helps map column names to format specifiers to display pandas DataFrame floats using particular formatting. If you need two decimal places:

df = pd.DataFrame({'A': [1.123, 2.456], 'B': [3.789, 4.012]}) # Here, making sure no one bothers us with decimals less than hundreths...when needed. formatted_df = df.style.format({'A': "{:.2f}", 'B': "{:.2f}"})

This outputs the DataFrame with 'A' and 'B' columns showing floats as strings formatted to two decimals.

Format, format everywhere (but with style)

Ever dreamt about having a global setting in pandas that applies all format rules? It's real. You can set a standard format for all float columns like:

# Global format is like your gravitational pull, everything just aligns. pd.options.display.float_format = '${:,.2f}'.format

Column-specific formats are no less. When the general setting doesn't cut it (say, one column is way too special), use to_string method or style.format for a more grand output. Here's how you can include a dollar sign for monetary values:

# Here, treating cents like cents, dollars like dollars…you got the money! df.to_string(formatters={'Price': '${:,.2f}'.format})

Or, using style.format:

# This column "Price"? Now, it's more than just a column with numbers. df.style.format({'Price': "${:,.2f}"})

The joy of separate, formatted columns

Why not create an additional column with formatted strings to enhance your data analysis?

# Yes, an entirely new column that looks "pretty." df['Formatted Price'] = df['Price'].map('${:,.2f}'.format)

This approach retains the integrity of the original data while offering a visually appealing reference.

Because not all formats are forever

The beauty of pd.option_context is that it allows temporary setting formats that print and disappear:

# It's like a format "cameo," makes an appearance, does the job, and leaves. with pd.option_context('display.float_format', '${:,.2f}'.format): print(df)

It provides a workaround for cases requiring quick display changes, like for reports or presentations.

A custom touch to your DataFrame

Flexible DataFrame-wide formatting can be achieved via the .applymap function. Alternatively, go element-wise with .map without creating additional columns or disrupting original data.

The inevitable quirks of styling

Styling in pandas is indeed versatile but bear in mind, it comes with its preparatory limitations. Styling won't affect the index display or influence the DataFrame's data storage capabilities. For printouts or exported files, remember, formatting is temporary.

Whenever your DataFrame absorbs fresh data, ensure that your chosen formatting method dynamically adjusts to the additional rows or columns to keep the consistency intact.

For any comprehensive reference or complex requirements, consult the documentation linked in the References section.