2

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 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.