pythonpandasdataframepandas-styles

How to print a pandas.io.formats.style.Styler object


I have the following code which produces a pandas.io.formats.style.Styler object:

import pandas as pd
import numpy as np

df = pd.DataFrame({'text': ['foo foo', 'bar bar'],
                 'number': [1, 2]})

df1 = df.style.set_table_styles([dict(selector='th', props=[('text-align', 'center')])])
df2 = df1.set_properties(**{'text-align': 'center'}).hide_index()
df2   # df2 is a pandas.io.formats.style.Styler object

How do I print df2 if I have more code running underneath the above script, for eg.:

import pandas as pd
import numpy as np

df = pd.DataFrame({'text': ['foo foo', 'bar bar'],
                 'number': [1, 2]})

df1 = df.style.set_table_styles([dict(selector='th', props=[('text-align', 'center')])])
df2 = df1.set_properties(**{'text-align': 'center'}).hide_index()
df2

np.round(0.536, 2)

I tried using the print statement but it's giving me an output as below:

import pandas as pd
import numpy as np

df = pd.DataFrame({'text': ['foo foo', 'bar bar'],
                 'number': [1, 2]})

df1 = df.style.set_table_styles([dict(selector='th', props=[('text-align', 'center')])])
df2 = df1.set_properties(**{'text-align': 'center'}).hide_index()
print(df2)

np.round(0.536, 2)
<pandas.io.formats.style.Styler object at 0x000000000B4FAFC8>
0.54

Any help would really be appreciated. Many thanks in advance.


Solution

  • I found the answer for this:

    import pandas as pd
    from IPython.display import display
    import numpy as np
    
    df = pd.DataFrame({'text': ['foo foo', 'bar bar'],
                     'number': [1, 2]})
    
    df1 = df.style.set_table_styles([dict(selector='th', props=[('text-align', 'center')])])
    df2 = df1.set_properties(**{'text-align': 'center'}).hide_index()
    display(df2)
    
    np.round(0.536, 2)