是否可以在IPython控制台中显示 pandas 样式? [英] Is it possible to display pandas styles in the IPython console?
问题描述
是否可以在熊猫样式中显示iPython控制台? Jupyter笔记本中的以下代码
Is it possible to display pandas styles in an iPython console? The following code in a Jupyter notebook
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前端?
Is it possible to achieve a similar result here, or is the style engine dependent on an html frontend?
在此先感谢您的帮助.
推荐答案
我相信样式器确实需要html前端,例如jupyter,即使它仅格式化数字(而不格式化字体或颜色).
I believe that the styler really requires an html frontend, like jupyter, even if it only formats numbers (and not fonts or colors).
例如参见此处使用Pandas Styler .
为了将一列转换为一种特定格式,应使用.map
方法:
In order to convert a column to a specific format, one should use the .map
method:
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']不再是数字,因此您无法再对数据帧进行正确排序.
The drawback is, that df['C'] is not a number anymore, so you cannot properly sort the dataframe anymore.
这篇关于是否可以在IPython控制台中显示 pandas 样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!