为什么 Pandas 中的 groupby 将计数放在现有列名下?

Why does groupby in Pandas place counts under existing column names?

我来自 R,不理解 pandas 中的默认 groupby 行为。我创建了一个数据框并按 'id' 列分组,如下所示:

d = {'id': [1, 2, 3, 4, 2, 2, 4], 'color': ["r","r","b","b","g","g","r"], 'size': [1,2,1,2,1,3,4]}
df = DataFrame(data=d)
freq = df.groupby('id').count()

当我检查结果数据框的 header 时,所有原始列都在那里,而不仅仅是 'id' 和 'freq'(或 'id' 和 'count').

list(freq)
Out[117]: ['color', 'size']

当我显示生成的数据框时,计数已替换未在计数中使用的列的值:

freq
Out[114]: 
    color  size
id             
1       1     1
2       3     3
3       1     1
4       2     2

我打算使用 groupby,然后按频率列进行过滤。我是否需要删除未使用的列并手动添加频率列?通常的做法是什么?

count 聚合 DataFrame 的所有列,排除 NaNs 值,如果需要 id 作为列使用 as_index=False 参数或 reset_index():

freq = df.groupby('id', as_index=False).count()
print (freq)
   id  color  size
0   1      1     1
1   2      3     3
2   3      1     1
3   4      2     2

所以如果在每一列中添加 NaNs 应该是不同的:

d = {'id': [1, 2, 3, 4, 2, 2, 4], 
     'color': ["r","r","b","b","g","g","r"],
      'size': [np.nan,2,1,2,1,3,4]}
df = pd.DataFrame(data=d)

freq = df.groupby('id', as_index=False).count()
print (freq)
   id  color  size
0   1      1     0
1   2      3     3
2   3      1     1
3   4      2     2

您可以指定列数:

freq = df.groupby('id', as_index=False)['color'].count()
print (freq)
   id  color
0   1      1
1   2      3
2   3      1
3   4      2

如果需要 countNaNs:

freq = df.groupby('id').size().reset_index(name='count')
print (freq)
   id  count
0   1      1
1   2      3
2   3      1
3   4      2

d = {'id': [1, 2, 3, 4, 2, 2, 4], 
     'color': ["r","r","b","b","g","g","r"],
      'size': [np.nan,2,1,2,1,3,4]}
df = pd.DataFrame(data=d)

freq = df.groupby('id').size().reset_index(name='count')
print (freq)
   id  count
0   1      1
1   2      3
2   3      1
3   4      2

谢谢 for pointed for another solution with value_counts, differences are explained :

freq = df['id'].value_counts().rename_axis('id').to_frame('freq').reset_index()
print (freq)
   id  freq
0   2     3
1   4     2
2   3     1
3   1     1