Giorgos Synetos
Giorgos Synetos

Reputation: 467

Combine multiple styles in pandas

I would like to ask if it is possible to combine different style formatting in pandas. For instance I want to combine the following 4 styles at once.

df.style.format({'vm_unity': '{:.2%}'}).bar(subset=['vm_unity'], align='mid', color=['#d65f5f', '#5fba7d'])
df.style.bar(subset=['vm_top'], align='mid', color=['#d65f5f', '#5fba7d'])
df.style.bar(subset=['vm_bot'], align='mid', color=['#d65f5f', '#5fba7d'])
df.style.bar(subset=['Sy'], align='mid', color=['#d65f5f', '#5fba7d'])

The way that I currently perform it is to combine them in a single line but I believe that it's not the most elegant way of doing it

df.style.format({'vm_unity': '{:.2%}'}).bar(subset=['vm_unity'], align='mid', color=['#d65f5f', '#5fba7d']).bar(subset=['vm_top'], align='mid', color=['#d65f5f', '#5fba7d']).bar(subset=['vm_bot'], align='mid', color=['#d65f5f', '#5fba7d']).bar(subset=['Sy'], align='mid', color=['#d65f5f', '#5fba7d'])

Can you please drop a line for a more effective way?

Upvotes: 9

Views: 15148

Answers (2)

KareemJ
KareemJ

Reputation: 804

1st Method

So there are multiple ways to use/apply multiple styles to a Styler/pandas dataframe. For me, the easiest and most straightforward way is to export styles, and that works as the following

myStyle = myStyler.export()

and in your case that's

style_1 = bar(subset=['vm_top'], align='mid', color=['#d65f5f', '#5fba7d']).export()

This will return a style object that you can then later apply using

from pandas.io.formats.style import Styler
Styler.use([style_1])

Cool thing about this function is that you can use either on or several different styles at once, by passing a list of styles. Therefore, to answer your question, just make sure that you export all styles that you want in advance, and then you can apply all at once.

2nd Method

is by using pandas.io.formats.style.Styler.where, in case you're interested in applying only two alternative styles.

Upvotes: 2

Roberto Fierimonte
Roberto Fierimonte

Reputation: 61

You can use the python's native linebreak \ and break the line afterwards. Your code would be:

df.style.format({'vm_unity': '{:.2%}'})\
        .bar(subset=['vm_unity'], align='mid', color=['#d65f5f', '#5fba7d'])\
        .bar(subset=['vm_top'], align='mid', color=['#d65f5f', '#5fba7d'])\
        .bar(subset=['vm_bot'], align='mid', color=['#d65f5f', '#5fba7d'])\
        .bar(subset=['Sy'], align='mid', color=['#d65f5f', '#5fba7d'])

Upvotes: 6

Related Questions