pythonpandasformattingnumber-formatting

Can you format pandas integers for display, like `pd.options.display.float_format` for floats?


I've seen this and this on formatting floating-point numbers for display in pandas, but I'm interested in doing the same thing for integers.

Right now, I have:

pd.options.display.float_format = '{:,.2f}'.format

That works on the floats in my data, but will either leave annoying trailing zeroes on integers that are cast to floats, or I'll have plain integers that don't get formatted with commas.

The pandas docs mention a SeriesFormatter class about which I haven't been able to find any information.

Alternatively, if there's a way to write a single string formatter that will format floats as '{:,.2f}' and floats with zero trailing decimal as '{:,d}', that'd work too.


Solution

  • Starting with Pandas 1.3.0, you can specify df.style.format(thousands=',') to use commas to separate thousands in floats, complex numbers, and integers.

    See docs: Styler.format