Is it possible to display pandas styles in an iPython console? The following code in a Jupyter notebook
JavaScript
x
9
1
import pandas as pd
2
import numpy as np
3
4
np.random.seed(24)
5
df = pd.DataFrame({'A': np.linspace(1, 10, 5)})
6
df = pd.concat([df, pd.DataFrame(np.random.randn(5, 1), columns=list('B'))],
7
axis=1)
8
df.style.format({'B': "{:.2%}"})
9
correctly produces
In the console I only get
JavaScript
1
3
1
In [294]: df.style.format({'B': "{:.2%}"})
2
Out[294]: <pandas.io.formats.style.Styler at 0x22f3f4fe780>
3
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.
Advertisement
Answer
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:
JavaScript
1
21
21
1
df = pd.DataFrame({'A': np.linspace(1, 5, 5)})
2
df = pd.concat([df, pd.DataFrame(np.random.randn(5, 1), columns=list('B'))],
3
axis=1)
4
5
df['C']=df['B'].map("{:.2%}".format)
6
7
print(df, end='nn')
8
print(df.dtypes)
9
10
A B C
11
0 1.0 1.329212 132.92%
12
1 2.0 -0.770033 -77.00%
13
2 3.0 -0.316280 -31.63%
14
3 4.0 -0.990810 -99.08%
15
4 5.0 -1.070816 -107.08%
16
17
A float64
18
B float64
19
C object
20
dtype: object
21
The drawback is, that df[‘C’] is not a number anymore, so you cannot properly sort the dataframe anymore.