How to return a specific cell that has a color style and font style for iloc [1,1]?

I have a dataframe and below is my color code:

   def color (val):
    if final.iloc[1,1]<final.iloc[1,0]:
        return "background-color: green"
    else:
        return "background-color: red"

I want to return only final.iloc[1,1]to have a green background color, if the code above was applied, our entire data frame has already turned green.

I also want to be final.iloc[1,1]able to change the font style, can anyone share some idea with me?

+4
source share
2 answers

You can use:

import pandas as pd
import numpy as np

np.random.seed(100)
df =  pd.DataFrame(np.random.randn(5, 3), columns=list('ABC'))
print (df)

def highlight_col(x):
    #copy df to new - original data are not changed
    df = x.copy()
    #set default values to all values
    df.loc[:,:] = 'background-color: ""'
    #set by condition
    if x.iloc[1,1]<x.iloc[1,0]:
        df.iloc[1,1] = 'background-color: red'
    else:
        df.iloc[1,1] = 'background-color: green'
    return df    

df.style.apply(highlight_col, axis=None)
+4
source
import pandas as pd
import numpy as np

ex1 = pd.DataFrame([
        [1, 2, 3],
        [2, 1, 4],
        [5, 3, 1]
    ], list('ABC'), list('XYZ'))

ex2 = pd.DataFrame([
        [1, 2, 3],
        [1, 9, 4],
        [5, 3, 1]
    ], list('ABC'), list('XYZ'))

def hl(x):
    r = 'background-color: red'
    g = 'background-color: green'
    c = g if x.iloc[1, 1] < x.iloc[1, 0] else r
    y = pd.DataFrame('', index=x.index, columns=x.columns)
    y.iloc[1, 1] = c
    return y

ex1.style.apply(hl, axis=None)

enter image description here

ex2.style.apply(hl, axis=None)

enter image description here

+2
source

Source: https://habr.com/ru/post/1675763/


All Articles