I'm experimenting/learning Python with a data set containing customers information.
The DataFrame structure is the following (these are made up records):
import pandas as pd
df1 = pd.DataFrame({'left_name' : ['James', 'Mary', 'John', 'Patricia'],
'left_age' : [30, 37, 30, 35],
'right_name' : ['Robert', 'Jennifer', 'Michael', 'Linda'],
'right_age' : [30, 31, 38, 35]})
print(df1)
left_name left_age right_name right_age
0 James 30 Robert 30
1 Mary 37 Jennifer 31
2 John 30 Michael 38
3 Patricia 35 Linda 35
Applying the transpose
method to df1
, we get the following view:
df2 = df1.T
print(df2)
0 1 2 3
left_name James Mary John Patricia
left_age 30 37 30 35
right_name Robert Jennifer Michael Linda
right_age 30 31 38 35
My goal is to apply some styling to df2
. Specifically,
- The
left_name
andright_name
rows should be highlighted in yellow; - The
left_age
andright_age
rows should be highlighted in blue.
I did some research before posting here and I managed to highlight one subset the following way:
df2.style.set_properties(subset = pd.IndexSlice[['left_name', 'right_name'], :], **{'background-color' : 'yellow'})
The problem is that I'm unable to combine multiple styles together. If I add an additional blue color for left_age
and right_age
using the same method as above, I "lose" the previous style.
Ideally, I would like to have a function that takes df2
as input and returns the styled DataFrame.