How to format IPython html display of Pandas dataframe?

前端 未结 3 1359
囚心锁ツ
囚心锁ツ 2020-11-30 22:12

How can I format IPython html display of pandas dataframes so that

  1. numbers are right justified
  2. numbers have commas as thousands separator
  3. lar
3条回答
  •  春和景丽
    2020-11-30 22:24

    On the OP's point 2:

    numbers have commas as thousands separator

    pandas (as of 0.20.1) does not allow overriding the default integer format in an easy way. It is hard coded in pandas.io.formats.format.IntArrayFormatter (the labmda function):

    class IntArrayFormatter(GenericArrayFormatter):
    
        def _format_strings(self):
            formatter = self.formatter or (lambda x: '% d' % x)
            fmt_values = [formatter(x) for x in self.values]
            return fmt_values
    

    I'm assuming is what you're actually asking for is how you can override the format for all integers: replace ("monkey patch") the IntArrayFormatter to print integer values with thousands separated by comma as follows:

    import pandas
    
    class _IntArrayFormatter(pandas.io.formats.format.GenericArrayFormatter):
    
        def _format_strings(self):
            formatter = self.formatter or (lambda x: ' {:,}'.format(x))
            fmt_values = [formatter(x) for x in self.values]
            return fmt_values
    
    pandas.io.formats.format.IntArrayFormatter = _IntArrayFormatter
    

    Note:

    • before 0.20.0, the formatters were in pandas.formats.format.
    • before 0.18.1, the formatters were in pandas.core.format.

    Aside

    For floats you do not need to jump through those hoops since there is a configuration option for it:

    display.float_format: The callable should accept a floating point number and return a string with the desired format of the number. This is used in some places like SeriesFormatter. See core.format.EngFormatter for an example.

提交回复
热议问题