user1769197
user1769197

Reputation: 2213

Pandas Styling: Conditional Formatting

I am apply the following formatting to the pandas data frame.

The data is as follow:

{'In / Out': {'AAA': 'Out',
  'BBB': 'In',
  'Total1': 'Out',
  'CCC': 'In',
  'DDD': 'In',
  'Total2': 'In'},
 'Mln': {'AAA': '$-1,707',
  'BBB': '$1,200',
  'Total1': '$-507',
  'CCC': '$245',
  'DDD': '$1,353',
  'Total2': '$1,598'},
 'US$ Mln': {'AAA': '$-258',
  'BBB': '$181',
  'Total1': '$-77',
  'CCC': '$32',
  'DDD': '$175',
  'Total2': '$206'}}

Can someone show me how to code this up ?

Upvotes: 0

Views: 1928

Answers (2)

Ch3steR
Ch3steR

Reputation: 20669

You have to use pd.IndexSlice in accordance with .loc.

Like this.

idx = pd.IndexSlice[['Total1', 'Total2'], :]
# If you don't want to hard-code use this
idx = pd.IndexSlice[df.index[[2, 5]], :]

Make style functions as you need.

# 1
def make_bold(val):
    return 'font-weight: bold'
# For italic use 'font-style: italic'
# 2
def apply_color(s):
    if s.isin(['In']).any():
        return ['color: green' for val in s]
    return ['color: red' for val in s]

You use df.style.applymap for element wise, df.style.apply for column/row wise.

s = df.style.applymap(
    make_bold, subset=pd.IndexSlice[["Total1", "Total2"], :] # subset=idx
).apply(apply_color, axis=1)
s

Output:

enter image description here


For # 3

You cannot apply style on index or columns Also per pandas style-docs, in Limitations section,

You can only style the values, not the index or columns

Upvotes: 2

Quang Hoang
Quang Hoang

Reputation: 150735

Let's try apply with axis=1:

df.style.apply(lambda x: ['color:red' if x['In / Out']=='Out' 
                           else 'color:green']*len(x), axis=1)

Output:

df.style.apply(lambda x: ['color:red' if x['In / Out']=='Out'
else 'color:green']*len(x), axis=1)

Upvotes: 2

Related Questions