0

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

Ahsu21
  • 21
  • 4

2 Answers2

0

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
BeRT2me
  • 12,699
  • 2
  • 13
  • 31
  • Yours work just that both ascending is True to achieve the output mentioned above. Thanks lad. U the best – Ahsu21 Jul 24 '22 at 06:30
0

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))
keramat
  • 4,328
  • 6
  • 25
  • 38