Raman Balyan Raman Balyan - 1 month ago 14
Python Question

Data extraction in Python Pandas

I am getting the results from the excel data by using groupby function of Pandas. My code for that is:

results = df.groupby(['Test Result', 'Risk Rating']).size().unstack(fill_value=0)


which is giving me the results in the form of this table:

Risk Rating CRITICAL HIGH LOW MEDIUM
Test Result
FAIL 8 0 9 4
PASS 0 13 23 37
SKIP 2 0 0 0


Now, I just want to get the result of all "FAIL" which should give me:

Risk Rating CRITICAL HIGH LOW MEDIUM
Test Result
FAIL 8 0 9 4


And, "FAIL" with just CRITICAL which should give me:

Risk Rating CRITICAL
Test Result
FAIL 8


How can I achieve this. Any help would be appreciated.

Answer

use .loc

results.loc['Fail']

would return values of the index 'Fail'

results.loc['Fail', 'Critical']

would return values of the index 'Fail' for Column 'Critical'

you can pass list for multiple columns or index such has:

results.loc['Fail', ['Critical','HIGH']]