Search code examples
pythonpandasdataframeapplypandas-styles

How to style pandas dataframe using a list of lists?


I have a pandas dataframe like:

enter image description here

I need to style it using a list of lists like:

[[3, 7, 4, 5],
[6, 17, 5, 10, 13, 16],
[7, 22, 6, 17, 19, 12],
[12, 26, 24, 25, 23, 18, 20],
[21, 20, 18, 27, 25]]

If R1 values are in first list color blue, if R2 values are in second list color blue and so on. In other words color numbers of each column if value is in the correspondent list.

I have tried:

def posclass(val):

    color = 'black'

    for i in range(5):
    
        if (val in list[i]):

            color = 'blue'

    return 'color: %s' % color

df.style.applymap(posclass,  subset=['R1','R2','R3','R4','R5'])

But this is not working properly applying each list to each column.

The desired result is a dataframe with colored numbers (those that matches in each column with each list).

enter image description here


Solution

  • Try something like this:

    df = pd.DataFrame(np.arange(40).reshape(-1,4), columns=[f'R{i}' for i in range(1,5)])
    

    Input df:

       R1  R2  R3  R4
    0   0   1   2   3
    1   4   5   6   7
    2   8   9  10  11
    3  12  13  14  15
    4  16  17  18  19
    5  20  21  22  23
    6  24  25  26  27
    7  28  29  30  31
    8  32  33  34  35
    9  36  37  38  39
    

    and

    list_l = [[3, 7, 4, 5],
    [6, 17, 5, 10, 13, 16],
    [7, 22, 6, 17, 19, 12],
    [12, 26, 24, 25, 23, 18, 20],
    [21, 20, 18, 27, 25]]
    

    Then:

    def f(x):
        colpos = df.columns.get_loc(x.name)
        return ['color: blue' if n in list_l[colpos] else '' for n in x]
    df.style.apply(f)
    

    Output:

    enter image description here