Home > other >  return zero instead of nothing when no rows in the corresponding index
return zero instead of nothing when no rows in the corresponding index

Time:04-15

I have the following code

count_by_month=df.groupby('month')['activity'].nunique()
month=list(range(0,12,1))
count_by_month.loc[count_by_week.index.isin(month),:] 

The above code return the following data:

month activity
3 12
7 7
9 15
12 10

I want the following it to return 0 instead of nothing when no item in the corresponding month value. i.e. if no data corresponding to month two then I want to include the index of 2 with zero in all columns. so the desired outbut should looks like the following:

month activity
1 0
2 0
3 12
4 0
5 0
6 0
7 7
8 0
9 15
10 0
11 0
12 10

I want to do this because I want to see the whole months set as an index on the X axses when plotting the data. If this is not possible then can we plot whole months index not only limited to where the data exist??

count_by_month.loc[count_by_week.index.isin(month),:].plot(kind='bar')

Thanks for suggestion..

CodePudding user response:

I figured out the solution: modifying the code to looks like the following work :

count_by_month.loc[count_by_week.index.isin(month),:].reindex(month, fill_value=0)
  • Related