democracii
democracii

Reputation: 89

Pandas: How to include a category in groupby that is not present in DataFrame

I used groupby function in Pandas Dataframe.

df :
Code  Level  
U-01   H
U-02   L
U-03   H
U-04   H
U-05   H
U-06   L

I wanted to count number of 'Code'

df = df.groupby('Level')['Code'].count()

Now result is,

Level  Code
H        4   
L        2

Actually, There are 3 category of "H", "L", "M" in Level.

In this case, There is no "M" category.

If there are no "H" or "M" or "L" category, I want to express category and "0" value.

** This df value is dynamic. **

My desired output table would look like:

Level  Code
H        4
M        0   
L        2

Pls help me!

Upvotes: 1

Views: 434

Answers (1)

jezrael
jezrael

Reputation: 863176

Use Series.reindex by list of all possible categories:

df1 = df.groupby('Level')['Code'].count().reindex(['H','M','L'], fill_value=0).reset_index()
print (df1)
  Level  Code
0     H     4
1     M     0
2     L     2

Upvotes: 3

Related Questions