是否可以在 IPython 控制台中显示 pandas 样式?

Is it possible to display pandas styles in the IPython console?

是否可以在 iPython 控制台中显示 pandas styles? Jupyter 笔记本中的以下代码

import pandas as pd
import numpy as np

np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 5)})
df = pd.concat([df, pd.DataFrame(np.random.randn(5, 1), columns=list('B'))],
               axis=1)
df.style.format({'B': "{:.2%}"})

正确生成

在控制台我只得到

In [294]: df.style.format({'B': "{:.2%}"})
Out[294]: <pandas.io.formats.style.Styler at 0x22f3f4fe780>

是否有可能在这里获得类似的结果,或者样式引擎是否依赖于 html 前端?

在此先感谢您的帮助。

我相信样式器确实需要一个 html 前端,例如 jupyter,即使它只格式化数字(而不是字体或颜色)。

参见例如这里 .

为了将列转换为特定格式,应使用 .map 方法:

df = pd.DataFrame({'A': np.linspace(1, 5, 5)})
df = pd.concat([df, pd.DataFrame(np.random.randn(5, 1), columns=list('B'))],
               axis=1)

df['C']=df['B'].map("{:.2%}".format)

print(df, end='\n\n')
print(df.dtypes)

     A         B         C
0  1.0  1.329212   132.92%
1  2.0 -0.770033   -77.00%
2  3.0 -0.316280   -31.63%
3  4.0 -0.990810   -99.08%
4  5.0 -1.070816  -107.08%

A    float64
B    float64
C     object
dtype: object

缺点是,df['C'] 不再是一个数字,因此您无法再对数据框进行正确排序。