div*_*obi 6 python console ipython pandas pandas-styles
是否可以在 iPython 控制台中显示pandas 样式?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%}"})
Run Code Online (Sandbox Code Playgroud)
正确产生
在控制台中我只得到
In [294]: df.style.format({'B': "{:.2%}"})
Out[294]: <pandas.io.formats.style.Styler at 0x22f3f4fe780>
Run Code Online (Sandbox Code Playgroud)
是否可以在这里实现类似的结果,或者样式引擎是否依赖于 html 前端?
预先感谢您的任何帮助。
我相信样式器确实需要一个 html 前端,比如 jupyter,即使它只格式化数字(而不是字体或颜色)。
请参阅此处使用 Pandas Styler。
为了将列转换为特定格式,应该使用以下.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
Run Code Online (Sandbox Code Playgroud)
缺点是 df['C'] 不再是数字,因此您无法再对数据帧进行正确排序。