“按计数分组”和“填充无”计数为0

2024-09-27 19:27:04 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是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()

我对此没有问题,但现在也没有工作

我想这是因为这次我只按一列分组,但当我按两列分组时,它仍然不起作用。我不知道为什么


Tags: dataframedfvaluestackcountlocation次数fill
1条回答
网友
1楼 · 发布于 2024-09-27 19:27:04

方法^{}用于排除缺失值的get计数,因此有必要为缺失值的检查列指定groupby之后的列,例如,这里测试了hour

df = df.groupby(["hour", "location"])['hour'].count().unstack(fill_value=0).stack()

但如果在groupby之后省略列,此方法将使用所有其他列进行计数。因此,如果使用:

print (df.groupby(["hour"]).count())
      location
hour          
1            1
2            2
3            2
6            3

还有另一列location,所以它使用它进行计数

如果使用:

print (df.groupby(["location"]).count())
          hour
location      
a            2
b            2
c            4

还有另一列hour,所以它使用它进行计数


但如果只有2列DataFrame,则有必要指定列以避免为空DataFrame,但它还取决于pandas version

print (df.groupby(["hour", "location"]).count())
Empty DataFrame
Columns: []
Index: [(1, a), (2, a), (2, b), (3, b), (3, c), (6, c)]

print (df.groupby(["hour", "location"])['hour'].count())
hour  location
1     a           1
2     a           1
      b           1
3     b           1
      c           1
6     c           3
Name: hour, dtype: int64

如果在方法^{}中使用了不关心缺失值,则不会测试缺失值,因此groupby之后不需要列:

df = df.groupby(["hour", "location"]).size().unstack(fill_value=0).stack()

print (df)
hour  location
1     a           1
      b           0
      c           0
2     a           1
      b           1
      c           0
3     a           0
      b           1
      c           1
6     a           0
      b           0
      c           3
dtype: int64

相关问题 更多 >

    热门问题