Search code examples
python-3.xpandasjupyter-notebookpandas-styles

pandas dataframe style formatting


In this example

import numpy as np
import pandas as pd
from itertools import product

df = pd.DataFrame({'Value':np.arange(10001,10007)}, 
    index=list(product(*[['A','B'],['a','b','c']])))
df.index = pd.MultiIndex.from_tuples(df.index, names=['Caps','Lower'])

df; df.style.format("{:,}")

when df is output to a Jupyter notebook, the values in column Caps are aligned to the top. However, when df.style.format("{:,}") is output in a Jupyter notebook, the values in column Caps are centered. Is there a way of forcing those values to be at the top? (i.e. they should be in the same line as a and not in the line as b).


Solution

  • You can use set_table_styles with selector:

    df.style.format("{:,}").set_table_styles([{'selector':'th',
                                               'props':[('vertical-align','top')]}])
    

    Output:

    enter image description here