0

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'}}

  • First, I am trying to make the entire third and sixth row bold. And I already got an error.
  • Second, I want the second, third and fourth column to be green when second column == In and red if second column == Out. How do I do this ?
  • Third, I want the only the text 'Total1' and 'Total2' (not the entire column) to be right-aligned, the other text in the same column can remain left aligned.

Can someone show me how to code this up ?

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.