'How to highlight subrow from DF

I have made a function which add subrows to an initial DF :

def AddSubrows(FullDF,DF):
    OutputDf = pd.DataFrame([]).reset_index(drop=True)
    for i in range(1,len(DF)):
        OutputDf = OutputDf.append(DF.loc[[i]])
        OutputDf = OutputDf.append(FullDF.loc[(FullDF['Issuer'] == DF['Issuer'][i]) & (FullDF['Wgt (P)'].apply(lambda x: float(x)) > 0) ])
    OutputDf = OutputDf.reset_index(drop=True)
    return OutputDf

Then I save it into excel and below is the output :

writer = pd.ExcelWriter("Test.xlsx", engine = 'xlsxwriter')
AddSubrows(DFFull,DF).to_excel(writer)
writer.save()
writer.close()

enter image description here

Is it possible to highlight subrows to make it more readable ?

Output wanted :

enter image description here

How can I do to make this excel file more readable ?



Solution 1:[1]

One way to do it would be to apply a conditional format to the range to highlight rows where the "Issuer" is the same as the previous row.

Something like this:

import pandas as pd


# Create a Pandas dataframe from some data.
df = pd.DataFrame({'Issuer': ['A', 'B', 'C', 'C', 'D', 'E', 'F', 'G', 'H',
                              'H', 'I', 'I', 'I', 'I', 'I', 'I', 'J' ],
                   'Wgt (D)': list(range(101, 118))})

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_conditional.xlsx', engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')

# Get the xlsxwriter workbook and worksheet objects.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Get the dimensions of the dataframe.
(max_row, max_col) = df.shape

# Create a format for the conditional format.
format1 = workbook.add_format({'bg_color': 'yellow'})

# Apply a conditional format to the required cell range.
worksheet.conditional_format(1, 0, max_row, max_col,
                             {'type':     'formula',
                              'criteria': '=$B2=$B1',
                              'format':   format1})

# Close the Pandas Excel writer and output the Excel file.
writer.save()

Output:

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jmcnamara