How to display pandas DataFrame of floats using a format string for columns?
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:
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:
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:
Or, using style.format
:
The joy of separate, formatted columns
Why not create an additional column with formatted strings to enhance your data analysis?
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 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.
Was this article helpful?