python-3.xpandasdataframeformattingoutput-formatting

Convert dataframe display float format to human readable for output display purpose only


I wish to display the dataframe column values in human readable format like 10, 100, 1K, 1M, 1B, etc.

So far, I could convert the scientific values (say) 1.111111e1 to numeric float format using pandas options with following arguments:

`display.float_format = '{:.2f}'.format

Note, 2 in the above line means 2 points of decimal. Change them as you like.

But, still the output is pretty hard to read when the column has so many varying numeric values. Especially in financial use case, with columns such as currency, turnover, profit, etc.

How to do this?

Note: I do not wish to convert the stored values into string format. I have calculations on the column values, so that is not feasible. Further, I won't create new columns for display purpose. So, df['new_col'] = df['col']/1000000 won't work either.

Sample dataframe:

pd.DataFrame([10.,100.,1000.,10000.,100000.,1000000.,10000000.,100000000.,1000000000.,10000000000.])

0   1.000000e+01
1   1.000000e+02
2   1.000000e+03
3   1.000000e+04
4   1.000000e+05
5   1.000000e+06
6   1.000000e+07
7   1.000000e+08
8   1.000000e+09
9   1.000000e+10

Solution

  • Use the following function with display.float_format argument in pandas options method to get the desired outcome.

    lambda x : '{:.2f}'.format(x) if abs(x) < 1000 else ('{:.2f} K'.format(x/1000) if abs(x) < 1000000 else ('{:.2f} M'.format(x/1000000) if abs(x) < 1000000000 else '{:.2f} B'.format(x/1000000000)))
    

    Output:

    0   10.00
    1   100.00
    2   1.00 K
    3   10.00 K
    4   100.00 K
    5   1.00 M
    6   10.00 M
    7   100.00 M
    8   1.00 B
    9   10.00 B