代码之家  ›  专栏  ›  技术社区  ›  davideps

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

  •  1
  • davideps  · 技术社区  · 8 年前

    我来自R,不理解熊猫默认的群居行为。我创建了一个数据帧,并按列“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,然后按频率列过滤。我需要删除未使用的列并手动添加频率列吗?通常的方法是什么?

    1 回复  |  直到 8 年前
        1
  •  3
  •   jezrael    8 年前

    count 聚合的所有列 DataFrame 带排除 NaN id as列使用 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
    

    所以如果添加 每列中的应为差异:

    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
    

    计数 具有 s:

    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