Raman Balyan
Raman Balyan

Reputation: 1063

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.

Upvotes: 2

Views: 180

Answers (2)

jezrael
jezrael

Reputation: 862641

I think you need ix what return Series or scalar value:

df1 = df.ix['FAIL']
print (df1)
Risk Rating
CRITICAL    8
HIGH        0
LOW         9
MEDIUM      4
Name: FAIL, dtype: int64

df1 = df.ix['FAIL', 'CRITICAL']
print (df1)
8

More complicated is if need return DataFrame - use boolean indexing with ix:

df1 = df.ix[df.index == 'FAIL', :]
print (df1)
Risk Rating  CRITICAL  HIGH  LOW  MEDIUM
Test Result                             
FAIL                8     0    9       4

df1 = df.ix[df.index == 'FAIL', ['CRITICAL']]
print (df1)
Risk Rating  CRITICAL
Test Result          
FAIL                8

Upvotes: 1

Steven G
Steven G

Reputation: 17122

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']]

Upvotes: 2

Related Questions