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?
One way to conditionally format your Pandas DataFrame is to highlight cells which meet certain conditions. To do so, we can write a simple function and pass that function into the Styler object using . apply() or .
Combine Two Columns Using + Operator By use + operator simply you can combine/merge two or multiple text/string columns in pandas DataFrame. Note that when you apply + operator on numeric columns it actually does addition instead of concatenation.
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'])
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.
is by using pandas.io.formats.style.Styler.where
, in case you're interested in applying only two alternative styles.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With