0

pivot table I have

df=pd.DataFrame({'Fruit':['Apple', 'Orange', 'Apple', 'Apple', 'Orange', 'Orange'],
            'Variety':['Fuji', 'Navel', 'Honeycrisp', 'Gala', 'Tangerine', 'Clementine'],
            'Count':[2, 5, 5, 1, 8, 4]})
df_pvt=pd.pivot_table(df, index=['Fruit','Variety'], values=['Count'], aggfunc=np.sum)
df=pd.concat([d.append(d.sum().rename((k, 'SubTotal'))) for k, d in df_pvt.groupby(level=0)]).append(df_pvt.sum().rename(('','GrandTotal')))

pivot table I want

How do I get the 'SubTotal', 'GrandTotal' and those values 'bold' and the rest of the font under Variety and Count as 'normal' font_weight, just like the image I have? Or any other way where I can have the subtotals and Grand totals pop out then rest of the dataframe.

  • Tough problem... you going to need to find away to select certain tags. I did something similiar with this post https://stackoverflow.com/a/55263917/6361531 – Scott Boston Oct 29 '19 at 13:12

1 Answers1

0

Tough problem... you going to need to find a way to select certain tags.

Let's try this bit of CSS selector coding for Jupyter notebooks.

def styleme(x):
    fw = 'bold' if 'Total' in x.name[1] else 'normal'
    l = [f'font-weight: {fw}']*len(x)
    return l

total_idx = np.where(~df.index.get_level_values(1).str.contains('Total'))

table_style = [{'selector':f'tbody tr th[id*=level1_row{i}]', 'props':[('font-weight','normal')]} for i in total_idx[0]]
df.style.apply(styleme, axis=1).set_table_styles(table_style)

Output:

enter image description here

However, as before, in the previous post, this formating didn't carry over to excel inthe to_excel output:

enter image description here

Scott Boston
  • 147,308
  • 15
  • 139
  • 187