Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas - highlighting cells in a dataframe

Tags:

python

pandas

I would like to test if the values of a column are bigger than another specific value of the same data frame. If a value is bigger, I want to highlight this specific cell.

I tried this:

import pandas as pd

b = pd.DataFrame([[5,7,3],[2,3,4],[8,4,7]])

for i in range(0, len(b)):
    for j in range(0, len(b.columns)):
        if  b.iloc[i][j] >  b.iloc[2][j]:
            b.style.applymap(lambda  x: 'background-color : blue' if b.iloc[i][j] >  b.iloc[2][j] else '') 

b

So in this example I want to check if 5 or 7 is bigger than 3 (column 1), 2 or 3 bigger than 4 (column 2) and 8 or 4 is bigger than 7.

It doesn't color anything... I hope someone can help me. Thx in advance.

like image 791
SeaSeaEss Avatar asked Oct 27 '22 13:10

SeaSeaEss


People also ask

How do I highlight a cell in pandas DataFrame?

To highlight a particular cell of a DataFrame, use the DataFrame's style. apply(~) method.

How do I use conditional formatting in pandas DataFrame?

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 .

How do you highlight a column in a DataFrame in Python?

You access the DataFrame's style property and to every column specified to highlight, you set “background-color: lightgreen” to their style configuration. This function returns a Styler object and not a DataFrame. For this and other styling options take a look at pandas style module.

What is ILOC () in Python?

The iloc() function in python is one of the functions defined in the Pandas module that helps us to select a specific row or column from the data set. Using the iloc() function in python, we can easily retrieve any particular value from a row or column using index values.


1 Answers

Try this solution:

import pandas as pd
import numpy as np

df = pd.DataFrame([[5,7,8],[2,3,4],[8,4,9]])

def highlight(s):
    '''
    highlight the maximum in a Series.
    '''
    is_max = s >= s[2]
    return ['background-color: blue' if v else '' for v in is_max]

df.style.apply(highlight, axis=0)

enter image description here

Note that the solution is based on the thread we discussed. The main change is the condition inside the highlight function. Using applymap works on a single cell each time, and has no access to its location in the dataframe. Using apply works on a single row each time and enables comparing to cell in the same row and different column.

like image 181
Shir Avatar answered Nov 15 '22 07:11

Shir