以下是MRE:
df = pd.DataFrame({"hour":[1,2,2,3,3,6,6,6], "location":["a","a", "b","b","c","c","c","c"]})
看起来是这样的:
hour location
0 1 a
1 2 a
2 2 b
3 3 b
4 3 c
5 6 c
6 6 c
7 6 c
当我按小时分组并计算每小时发生的次数时,我得到
df.groupby(["hour"]).count()
>>> location
hour
1 1
2 2
3 2
6 3
在中,您希望填写第4小时和第5小时,并将其计数设置为0
以下是我的愿望:
location
hour
1 1
2 2
3 2
4 0
5 0
6 3
以前我用过
df.groupby(["hour", "location"]).count().unstack(fill_value=0).stack()
我对此没有问题,但现在也没有工作
我想这是因为这次我只按一列分组,但当我按两列分组时,它仍然不起作用。我不知道为什么
方法^{} 用于排除缺失值的get计数,因此有必要为缺失值的检查列指定
groupby
之后的列,例如,这里测试了hour
:但如果在
groupby
之后省略列,此方法将使用所有其他列进行计数。因此,如果使用:还有另一列
location
,所以它使用它进行计数如果使用:
还有另一列
hour
,所以它使用它进行计数但如果只有2列
DataFrame
,则有必要指定列以避免为空DataFrame
,但它还取决于pandas version:如果在方法^{} 中使用了不关心缺失值,则不会测试缺失值,因此
groupby
之后不需要列:相关问题 更多 >
编程相关推荐