Ad

Add Possible Values From List To Groupby Result

- 1 answer

I have a list of possible results:

list(TEST_RESULT_PRIORITY.keys())

['Failed',
 'Inconclusive',
 'Passed',
 'Error',
 'NotImplemented',
 'NonTestable',
 'None']

and I do a groupby of a dataframe and get:

df.groupby(['Result']).size()

Result
Failed           144
Inconclusive      29
NonTestable       15
None            4820
Passed            45

I would like to add to the result of the groupby the options from the first list (or dictionary keys, whatever is easier) that don't show because don't exist in the data frame. So I would get something like this (order alphabetically would be easier):

Result
Error              0
Failed           144
Inconclusive      29
NotImplemented     0
NonTestable       15
None            4820
Passed             0
Passed            45

Any ideas? Thanks!

Ad

Answer

Use Series.reindex with Series.sort_index:

s = (df.groupby(['Result'])
      .size()
      .reindex(list(TEST_RESULT_PRIORITY.keys()), fill_value=0)
      .sort_index())
print (s)
Result
Error                0
Failed             144
Inconclusive        29
NonTestable         15
None              4820
NotImplemented       0
Passed              45
dtype: int64

Or add sorted:

s = (df.groupby(['Result'])
      .size()
      .reindex(sorted(list(TEST_RESULT_PRIORITY.keys())), fill_value=0))
print (s)
Result
Error                0
Failed             144
Inconclusive        29
NonTestable         15
None              4820
NotImplemented       0
Passed              45
dtype: int64
Ad
source: stackoverflow.com
Ad