October 2019
Beginner to intermediate
674 pages
16h 43m
English
Apart from the in-built functions, pandas provides us with the option to write our own functions to be used for styling. Let's write a function to change the background color of negative values to red:
def color_negative(val):
color = 'red' if val < 0 else 'green'
return 'background-color: %s' % color
Such functions can be applied as a styling option through the apply() and applymap methods of pandas. The applymap method applies the function elementwise. The apply() method can be used to apply styles either row-wise or column-wise by setting the axis parameter to 1 or 0. Setting the axis to None applies the function table-wise. Here, our intended operation is elementwise. Let's use applymap:
rand_df.style.applymap(color_negative) ...
Read now
Unlock full access