9

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?

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
Giorgos Synetos
  • 457
  • 3
  • 6
  • 13
  • I don't have an answer to this, but I think the [Zen of Python](https://www.python.org/dev/peps/pep-0020/) would guide that the former approach is *much* preferred (in lieu of a more concise approach perhaps posed here). – blacksite May 18 '17 at 13:57
  • I've already posted an answer down below, but may I ask what you mean with 'more effective way'? Because I think that your way is already good and readable enough. – KareemJ Jun 08 '19 at 10:40

2 Answers2

6

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'])
2

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.

Community
  • 1
  • 1
KareemJ
  • 744
  • 10
  • 15