Pandas DataFrame formatting

人盡茶涼 提交于 2019-12-22 07:55:07

问题


I have a pandas DataFrame with mixed values in it. I am working in Ipython notebook while developing it. When displaying the dataframe I would like it to display to facilitate easier reading. At the moment I am using python string formatting to display all floats to 4 decimals and to add thousand separators.

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

Ideally I would like to E.g. Display Values over 10000 without decimals, fractions with 4 significant digits etc. Is there a way that I can use the python string formatting syntax to achieve this? I know i can do it for individual column, but am looking to to this purely for the display within the notebook?


回答1:


You can pass a function to float_format, so can be anything

In [1]:

df = DataFrame(dict(A = [1.2345,10000.12345,1]))
df
Out[1]:
A
0    1.23450
1    10000.12345
2    1.00000
3 rows × 1 columns
In [4]:

pd.set_option('display.float_format',
      lambda x: '{:,.4f}'.format(x) if abs(x) < 10000 else '{:,.0f}'.format(x))
In [5]:

df
Out[5]:
A
0   1.2345
1   10,000
2   1.0000
3 rows × 1 columns


来源:https://stackoverflow.com/questions/23544891/pandas-dataframe-formatting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!