【问题标题】:Why does groupby in Pandas place counts under existing column names?为什么 Pandas 中的 groupby 将计数放在现有列名下?
【发布时间】:2018-05-09 18:30:27
【问题描述】:

我来自 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()

当我检查结果数据帧的标题时,所有原始列都在那里,而不仅仅是“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,然后按频率列进行过滤。我是否需要删除未使用的列并手动添加频率列?通常的做法是什么?

【问题讨论】:

  • When I check the header of the resulting dataframe 你没有这样做,因为你在做list(df) 而不是list(freq)list(freq) 确实给了['color', 'size']
  • 若要仅获取一列的频率,请使用value_counts() 而不是 groupby。
  • 将代码修复为列表(频率)。

标签: pandas pandas-groupby


【解决方案1】:

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

感谢Bharath 指出value_counts 的另一个解决方案,解释了here 的不同之处:

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

【讨论】:

  • 也许 Op 正在寻找 df['id'].value_counts().to_frame('freq')
  • 谢谢@jezrael。这产生了我正在寻找的答案freq = df.groupby('id').size().reset_index(name='count')
猜你喜欢
  • 2018-08-31
  • 2021-12-29
  • 2013-10-31
  • 2018-11-25
  • 1970-01-01
  • 2021-02-01
  • 1970-01-01
  • 2016-03-22
相关资源
最近更新 更多