6

having dataframe summary being called directly from jupyter cell

summary #(Shift + Enter)

how can I make the highlighted row only (last row) in bold font?

enter image description here

3 Answers 3

18

Please, please provide the code to at least generate the dataframe you are posting.

For what you want, you can use style.applymap() function. The rest is to find the correct properties of font that can be set to bold and how to set index of last row.

import pandas as pd

def df_style(val):
    return "font-weight: bold"

summary = pd.DataFrame([[0, 0, 0, 0, 0], [1620, 203, 392, 651, 2236]],
                       index=["None", "Total"])

# get a handle on the row that starts with `"Total"`, i.e., the last row here
last_row = pd.IndexSlice[summary.index[summary.index == "Total"], :]
# and apply styling to it via the `subset` arg; first arg is styler function above
summaryStyled = summary.style.applymap(df_style, subset=last_row)

display(summaryStyled)

And below is the output:

enter image description here

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

4 Comments

@B.Malysz I mean to post the code to generate the dataframe you posted in the picture. instead of letting others back-engineering. I assume that's nothing confidential.
This code is not working for my case. I also want to ask, where do you use df_style function?
@DionisiusPratama Indeed it was mistaken, now fixed; function is used as the first argument to style.applymap.
Styler.applymap has been deprecated. Use Styler.map instead.
6

try this:

def highlight_max(x):
    return ['font-weight: bold' if v == x.loc[4] else ''
                for v in x]
df = pd.DataFrame(np.random.randn(5, 2))
df.style.apply(highlight_max)

enter image description here

2 Comments

I got this error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). Do you have any idea on how to solve it?
loc[4] is wrong sintax. Use iloc[4] inside.
3

A better option for the 'last row' would be.

def highlight_last(x):
    '''
    highlight the last row in a Series BOLD.
    '''
    return ['font-weight: bold' if v == x.iloc[-1] else '' for v in x]

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

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.