How to use User-defined Function In Python

  • We can modify DataFrame using a user-defined function: With the help of this function, we can customizing the font color of positive data values inside the data frame.

Python3




# function for set text color of positive
# values in Dataframes
def color_positive_green(val):
    """
    Takes a scalar and returns a string with
    the css property `'color: green'` for positive
    strings, black otherwise.
    """
    if val > 0:
        color = 'green'
    else:
        color = 'black'
    return 'color: %s' % color
 
df.style.applymap(color_positive_green)


Output: 

User-Defined Function

Set Pandas dataframe background Color and font color in Python

As we know, the basic idea behind styling is to make more impactful for the end-user readability. We can make changes like the color and format of the data visualized in order to communicate insight more efficiently. For the more impactful visualization on the pandas DataFrame, generally, we DataFrame.style property, which returns styler object having a number of useful methods for formatting and visualizing the data frames.

Similar Reads

Using DataFrame.style property

df.style.set_properties: By using this, we can use inbuilt functionality to manipulate data frame styling from font color to background color....

Using User-defined Function

...

Using Seaborn Library

...