Search code examples
pythonpandaspython-applymap

call multiple argument function in applymap in python


I wrote a function for giving colors to the variables for pandas data frame. there I used two arguments first one is variables list and another is threshold values list(i'am having only two values in the list e.g, say 30 and 50) for color the variables and function as follows::

def color_code(val,values):
    if val <= values[0]:
       color = 'green'
    elif values[0]<val<=values[1]:
       color = 'yellow'
    elif val >values[1]:
       color = 'red'
    return 'background-color: %s' % color

Now I want to call this function.For that i tried the following.

df1=df.style.applymap(color_code,subset=['col1','col2'],values=[30,50])

but the above call is not working for me.

Can anyone help me to solve this.

Thanks in advance.


Solution

  • You can try this:

    def color_code(values):
        def color_code_by_val(val):
            if val <= values[0]:
                color = 'green'
            elif values[0]<val<=values[1]:
                color = 'yellow'
            elif val >values[1]:
                color = 'red'
            return 'background-color: %s' % color
        return color_code_by_val
    

    Then your call should be:
    df1=df.style.applymap(color_code([30,50]), subset=['col1','col2'])