Use Pandas Style to Format index/rows of DataFrame

4.8k views Asked by At

Please can someone help with how to use pandas style to set formatting by row?

I have a dataframe which will have 10-20 rows and 3-4 columns, most of the data needs to be presented as a percentage to 2-decimal places but some rows are floats, integers or multiples (i.e. 12.5x). There are loads of examples of how to format columns or conditionally format rows by colour but none seem to (apologies if I am mistaken) do number formatting by row/index.

In the example below I can set the table generically to be :.2% and colour the row and make 1 column be 1.1x

data =  pd.DataFrame(np.random.randn(5, 3), columns=list('ABC'))

def row_format(x):
    return 'background-color: red'

data.style.format("{:.2%}").\
           format({'C':'{:.1f}x'}).\
           applymap(row_format, subset=pd.IndexSlice[2, :])

enter image description here

But the same formatting doesn't work on rows in the dictionary and I can't work out the correct function for row_format() to set that row to be (say) a row of integers.

Any help appreciated.

1

There are 1 answers

0
pontificating_panda On

According to the docs formatter can take a dictionary of column names or a subset of column names. However it appears you can set the subset to a pd.IndexSlice[] within pd.style.format() and it will work

x = df.T
x = x.style.format("{:.1%}", na_rep='-')
x = x.format(formatter="{:.2f}", subset=pd.IndexSlice[['rar', 'beta', 'ir'], :])

Hope someone else can find this useful