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

我只是一个虾纸丫 提交于 2019-12-11 15:08:20

问题


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%}"})

correctly produces

In the console I only get

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

Is it possible to achieve a similar result here, or is the style engine dependent on an html frontend?

Thanks in advance for any help.


回答1:


I believe that the styler really requires an html frontend, like jupyter, even if it only formats numbers (and not fonts or colors).

See e.g. here Using Pandas Styler.

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

The drawback is, that df['C'] is not a number anymore, so you cannot properly sort the dataframe anymore.



来源:https://stackoverflow.com/questions/58505444/is-it-possible-to-display-pandas-styles-in-the-ipython-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!