Skip to content

Instantly share code, notes, and snippets.

@clintval
Created February 25, 2018 00:28
Show Gist options
  • Select an option

  • Save clintval/eae1bc11e989badfaff776597432e092 to your computer and use it in GitHub Desktop.

Select an option

Save clintval/eae1bc11e989badfaff776597432e092 to your computer and use it in GitHub Desktop.
Format DataFrame's with better integer representation e.g. 1,000,00.00
import contextlib
import sys
import pandas as pd
try:
import pandas.io.formats.format as pf
except ImportError:
import pandas.formats.format as pf
except ImportError:
import pandas.core.format as pf
@contextlib.contextmanager
def pandas_int_format(float_fmt='scientific', precision=2):
"""Context manager to format pandas DataFrame objects using comma
seperator for thousands places and scientific notation for floating point.
Will revert to decimals if numbers are not floats.
http://stackoverflow.com/a/29663750
Parameters
----------
float_fmt : str
Floats presentation can either be `scientific` or `fixed`.
precision : int
The precision of the presented floating point numbers.
"""
orig_float_format = pd.options.display.float_format
orig_int_format = pf.IntArrayFormatter
if float_fmt == 'scientific':
pd.options.display.float_format = f'{{:.{precision}e}}'.format
elif float_fmt == 'fixed':
pd.options.display.float_format = f'{{:0,.{precision}f}}'.format
else:
raise ValueError('Only `scientific`or `fixed` float_fmt allowed.')
class IntArrayFormatter(pf.GenericArrayFormatter):
def _format_strings(self):
formatter = self.formatter or '{:,d}'.format
fmt_values = [formatter(x) for x in self.values]
return fmt_values
pf.IntArrayFormatter = IntArrayFormatter
yield
pf.IntArrayFormatter = orig_int_format
pd.options.display.float_format = orig_float_format
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment