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

使pandas dataframe group by count具有列名

  •  1
  • Chubaka  · 技术社区  · 7 年前

    在Python3.6和Pandas0.19.0中,有一个数据帧“df”

    id
    abc
    abc
    def
    

    SELECT id, COUNT(1) AS id_count FROM table group by id
    

    理想回报:

    id  id_count
    abc 2
    def 1
    

    我试过:

    print (df.groupby(['id'])['id'].count())
    

    id
    abc 2
    def 1
    
    print (df.groupby(['id'])['id'].transform('count'))
    

    0    2
    1    1
    

    有什么想法吗?谢谢您!

    1 回复  |  直到 7 年前
        1
  •  3
  •   cs95 abhishek58g    7 年前

    在聚合函数中使用此基于词典的格式 groupby .

    df.groupby('id', as_index=False)['id'].agg({'id_count':'count'})
    
        id  id_count
    0  abc         2
    1  def         1