4

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

Bartek Malysz
  • 922
  • 5
  • 14
  • 37

3 Answers3

14

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

tutejszy
  • 602
  • 7
  • 22
John
  • 348
  • 3
  • 15
  • 1
    @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. – John Aug 22 '18 at 11:42
  • This code is not working for my case. I also want to ask, where do you use ```df_style``` function? – Dionisius Pratama Mar 12 '21 at 16:00
  • 1
    @DionisiusPratama Indeed it was mistaken, now fixed; function is used as the first argument to `style.applymap`. – Mustafa Aydın Nov 23 '21 at 19:15
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

Alok Mishra
  • 694
  • 5
  • 20
2

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]
Omar Ahmed
  • 139
  • 8
  • 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](/help/how-to-answer). – Community Apr 12 '22 at 00:05