首页 > 解决方案 > How to define color of specific cell in pandas dataframe based on integer position (e.g., df.iloc[1,1]) with df.style?

问题描述

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

标签: pythonpandasdataframepandas-styles

解决方案


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')
})

推荐阅读