6

Is it possible to define a color of a specific cell in a pandas dataframe based on integer position like for instance df.iloc[1,1] with pandas styling? https://pandas.pydata.org/pandas-docs/stable/style.html

Something like the following would be nice, but is not working.

def style_specific_cell(val):

    color = 'lightgreen'
    val.iloc[2, 8] = color
    return XYZ

df = df.style.applymap(style_specific_cell, subset=['Column1']
4

1 回答 1

7

Use style.Styler.apply with helper DataFrame of styles:

def style_specific_cell(x):

    color = 'background-color: lightgreen'
    df1 = pd.DataFrame('', index=x.index, columns=x.columns)
    df1.iloc[2, 8] = color
    return df1

df.style.apply(style_specific_cell, axis=None)

pic

Sample DataFrame:

df = pd.DataFrame({
        'A':list('abcdef'),
         'B':[4,5,4,5,5,4],
         'C':[7,8,9,4,2,3],
         'D':[1,3,5,7,1,0],
         'E':[5,3,6,9,2,4],
         'F':list('aaabbb')
})
于 2018-10-19T07:45:08.063 回答