return 当相应索引中没有行时,零而不是空

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

我有以下代码

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

以上代码return以下数据:

month activity
3 12
7 7
9 15
12 10

我希望在相应的月份值中没有项目时将其跟随到 return 0 而不是什么都没有。即,如果没有对应于第二个月的数据,那么我想在所有列中包含 2 和零的索引。所以所需的输出应该如下所示:

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

我想这样做是因为我想在绘制数据时将整个月份设置为 X 轴上的索引。 如果这不可能,那么我们能否绘制整个月的指数,而不仅限于数据存在的地方??

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

感谢建议..

我想出了解决办法: 将代码修改为如下所示:

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