While studying Pandas Style, I got to the following:
def highlight_max(s):
'''
highlight the maximum in a Series yellow.
'''
is_max = s == s.max()
return ['background-color: yellow' if v else '' for v in is_max]
How should I read is_max = s == s.max()
?
s == s.max()
will evaluate to a boolean (due to the ==
in between the variables). The next step is storing that value in is_max
.
In pandas s
is very often Series
(column in DataFrame
).
So you compare all values in Series
with max
value of Series
and get boolean mask. Output is in is_max
. And then set style 'background-color: yellow'
only to cell of table where is True
value - where is max value.
Sample:
s = pd.Series([1,2,3])
print (s)
0 1
1 2
2 3
dtype: int64
is_max = s == s.max()
print (is_max)
0 False
1 False
2 True
dtype: bool
The code
is_max = s == s.max()
is evaluated as
is_max = (s == s.max())
The bit in parentheses is evaluated first, and that is either True
or False
. The result is assigned to is_max
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With