简体   繁体   English

在 iPython 中使用 style.format 打印 pandas df

[英]Print pandas df with style.format in iPython

Minimal working example:最小工作示例:

import pandas as pd
df = pd.DataFrame({
    'letters':('A', 'B', 'C'),
    'numbers':(0.1111, 0.2222, 0.3333)
}).set_index('letters')
df.style.format('{:.2f}')

Result:结果:

Out[4]: <pandas.io.formats.style.Styler at 0x7f963f826eb8>

What I want:我想要的是:

Something similar to the default Jupyter output:类似于默认的 Jupyter 输出:

jupyter_output

One way to do this is using the formatters or float_format keyword of df.to_string这样做的一种方法是使用formattersfloat_format的关键字df.to_string

>>> print(df.to_string(float_format=lambda x: '{:.2f}'.format(x)))
         numbers
letters         
A           0.11
B           0.22
C           0.33

float_format will apply a function to all floats to format, while formatters can accept a list or dict to format specific columns in the dataframe. float_format将函数应用于所有浮点数以进行格式化,而格式化程序可以接受列表或字典来格式化数据帧中的特定列。

Minimal working example:最小的工作示例:

import pandas as pd
df = pd.DataFrame({
    'letters':('A', 'B', 'C'),
    'numbers':(0.1111, 0.2222, 0.3333)
}).set_index('letters')
df.style.format('{:.2f}')

Result:结果:

Out[4]: <pandas.io.formats.style.Styler at 0x7f963f826eb8>

What I want:我想要的是:

Something similar to the default Jupyter output:类似于默认的Jupyter输出:

jupyter_output

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

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