简体   繁体   English

Pandas DataFrame格式化

[英]Pandas DataFrame formatting

I have a pandas DataFrame with mixed values in it. 我有一个带有混合值的pandas DataFrame。 I am working in Ipython notebook while developing it. 我正在开发Ipython笔记本时使用它。 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. 目前我正在使用python字符串格式化显示所有浮点数到4位小数并添加千位分隔符。

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

Ideally I would like to Eg 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? 理想情况下,我想Eg显示值超过10000没有小数,分数有4位有效数字等。有没有办法,我可以使用python字符串格式化语法来实现这一点? I know i can do it for individual column, but am looking to to this purely for the display within the notebook? 我知道我可以为个人专栏做这件事,但我期待这纯粹用于笔记本内的显示器?

You can pass a function to float_format , so can be anything 你可以将一个函数传递给float_format ,所以可以是任何东西

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM