therion
therion

Reputation: 445

Pandas Styling - Coloring cells of specific columns instead of entire DataFrame

I wrote the following block of code to colour some cells in my dataframe.

def applycolor(dtf):

        return ['background-color: lightgreen' if x >= 1500  else 
        ('background-color: lightskyblue' if 1000 <= x < 1500  else 
        'background-color: pink' if 750 <= x < 1000 else
        'background-color: wheat' if  550 <= x < 750 else 
        'background-color: paleturquoise' if 330 <= x < 550  else 
        'background-color: darkseagreen' if 150 <= x < 330 else 'background-color: default') for x in dtf]    


cs1 = cs.style.apply(applycolor, axis=0)

This gave me a result as shown in the image.

enter image description here However, I only want the colors to be rendered for the figures specified in df['$-Score']. But this styling appended colours to all the relevant numerics of the dataframe as seen.

I tried to change last line of the list comprehension to include only the particular column of the dataframe like so: .....if 150 <= x < 330 else 'background-color: default') for x in dtf['$-Score']- but it returned an error.

Have tried looking for the specific answer, but haven't been able to find it. Any ideas?

Alternatively, a SAMPLE DATAFRAME:

    A    B   C
0   83  76  30
1   34  17  44
2   72  16  94
3   24  94  27
4   98  36  35
5   41  77  39
6   65  54  18
7   85  1   59
8   12  79  2
9   33  57  76
10  66  69  100
11  99  51  89
12  24  74  32
13  51  98  63
14  63  36  82
15  53  52  65

I only want numbers between 55 and 58 to be coloured red in column B and Blue between 84 and 87 in column C only.

How can I go about it?

Upvotes: 2

Views: 7886

Answers (2)

Oleks
Oleks

Reputation: 31

Just use subset property


df.style.apply(your_func, subset=['column_name'])

Upvotes: 1

wkzhu
wkzhu

Reputation: 1660

Style.apply works just like DataFrame.apply in that the dataframe is broken into series, and in your case you want to do something different based on each series's name (i.e., column name). So the below example can be extended for your purposes:

def apply_formatting(col):
    if col.name == 'a':
        return ['background-color: red' if c > 50 else '' for c in col.values]
    if col.name == 'b':
        return ['background-color: green' if c > 10 else '' for c in col.values]
    if col.name == 'c':
        return ['background-color: blue' if c > 30 else '' for c in col.values]

data = pd.DataFrame(
    np.random.randint(0, 100, 30).reshape(10, 3), columns=['a', 'b', 'c'])

data.style.apply(apply_formatting)  # axis=0 by default

Here is the result on the random data:

enter image description here

Upvotes: 2

Related Questions