Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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']
like image 857
Raphael Avatar asked Oct 19 '18 07:10

Raphael


People also ask

How do I get a particular cell value in a DataFrame?

Select Cell Value from DataFrame Using df['col_name']. values[] We can use df['col_name']. values[] to get 1×1 DataFrame as a NumPy array, then access the first and only value of that array to get a cell value, for instance, df["Duration"].

How do you specify a cell in a DataFrame in Python?

You can set cell value of pandas dataframe using df.at[row_label, column_label] = 'Cell Value'. It is the fastest method to set the value of the cell of the pandas dataframe. Dataframe at property of the dataframe allows you to access the single value of the row/column pair using the row and column labels.

How do I filter data based on conditions in pandas?

You can use df[df["Courses"] == 'Spark'] to filter rows by a condition in pandas DataFrame.

How do I use conditional formatting in pandas?

Conditional cell highlighting. 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 .


1 Answers

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')
})
like image 51
jezrael Avatar answered Sep 20 '22 13:09

jezrael