I have a dataframe that includes students' id and grades in different subjects, and I want the lessons that have passed (> 10) to be shown in green and lessons that have been failed to be shown in red.
import pandas as pd
df=pd.DataFrame({"Math":[2,20,12,12,5,10,9.75,17],"Physics":[3,16,13,18,6,10,9,10],"chemistry":[10,19,5,17,16.5,14.75,10,4]},index=[331,332,333,334,335,336,337,338])
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 .
To highlight a particular cell of a DataFrame, use the DataFrame's style. apply(~) method.
def colors(val):
color = 'red' if val <= 10 else 'green'
return 'color: %s' % color
df.style.applymap(colors)
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