Home > other >  How do I group by the outcome and severity header in xlsxwriter
How do I group by the outcome and severity header in xlsxwriter

Time:07-24

can anybody help me categorize the header of outcome and severity to show the FAIL and HIGH values highlighted in red at the top while the rest will be in descending order using xlsxwriter. I really can't understand how the structure works.

enter image description here

To an outcome of something like this. To order the FAIL first and afterwards the severity of HIGH.

enter image description here

CodePudding user response:

Given:

df = pd.DataFrame({'Outcome':['Pass', 'Fail', 'Pass', 'Fail', 'Fail'], 'Severity':['High', 'Medium', 'Low', 'Medium', 'High']})

  Outcome Severity
0    Pass     High
1    Fail   Medium
2    Pass      Low
3    Fail   Medium
4    Fail     High

Doing:

# Make your columns custom ordered categoricals:
df.Outcome = pd.Categorical(df.Outcome, ordered=True, categories=['Fail', 'Pass'])
df.Severity = pd.Categorical(df.Severity, ordered=True, categories=['Low', 'Medium', 'High'])

# Sort, the sort will follow the category order, instead of Alphabetical.
df = df.sort_values(['Outcome', 'Severity'], ascending=[True, False], ignore_index=True)
print(df)

Output:

  Outcome Severity
0    Fail     High
1    Fail   Medium
2    Fail   Medium
3    Pass     High
4    Pass      Low

CodePudding user response:

You need to just sort your data by the Outcome column, then by the edited Severity column. Use:

df.sort_values(['Outcome', 'Severity'], key= lambda x: x.replace('Low', 2).replace('Medium', 1).replace('High', 0))
  • Related