V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
yearliny
V2EX  ›  Python

求助: Python pandas 分组统计问题

  •  
  •   yearliny · 2017-10-28 13:40:56 +08:00 via Android · 3273 次点击
    这是一个创建于 2372 天前的主题,其中的信息可能已经有所发展或是发生改变。
    有一个数据为:

    index|years|types
    -|-|-
    0|2010|auto
    1|2010|auto
    2|2011|manual
    3|2006|manual
    4|2015|auto
    5|2015|auto

    我希望能统计每年出现 auto/manual 的类型次数,最好还能把以年作为索引进行排列,达成下面的效果:
    auto. manual
    2006. 0. 1
    2010. 2. 0
    2011. 0. 1
    2015. 2. 0

    我应该怎么才能统计出那样的效果?
    ////备注:不太懂我的 markdown 表格为什么不显示
    8 条回复    2017-10-28 16:24:06 +08:00
    yearliny
        1
    yearliny  
    OP
       2017-10-28 13:55:27 +08:00 via Android
    格式被 V2EX 转的不是很清楚,编辑次数太多了也无法继续编辑了。希望大家能耐心看完,给我一点帮助。Google 了很多,还是不知道怎么做,先谢谢各位了。
    lt0136
        2
    lt0136  
       2017-10-28 13:56:24 +08:00   ❤️ 1
    df.groupby([df['years'], df['types']]).count().unstack() (未测试:-D )
    思路是先 groupby 统计次数,然后 unstack 列变行
    yearliny
        3
    yearliny  
    OP
       2017-10-28 14:28:03 +08:00 via Android
    @lt0136 太谢谢了~~~
    zhusimaji
        4
    zhusimaji  
       2017-10-28 14:28:14 +08:00   ❤️ 1
    zhusimaji
        5
    zhusimaji  
       2017-10-28 14:29:07 +08:00   ❤️ 1
    偷懒了,给 dataframe 加上了一列然后 groupby 统计了一下
    yearliny
        6
    yearliny  
    OP
       2017-10-28 14:29:44 +08:00 via Android
    @lt0136 再次感谢,刚刚一不小心还没打完字就发过去了,把你回答中的 count()改成 size()就能出来我预期的效果了,还是需要多多学习研究一下,谢谢你的帮助。

    df.groupby([df['years'], df['types']]).count().unstack()
    yearliny
        7
    yearliny  
    OP
       2017-10-28 14:34:00 +08:00 via Android
    @zhusimaji 很感谢你的帮助,我研究一下你的方法~😊
    fffflyfish
        8
    fffflyfish  
       2017-10-28 16:24:06 +08:00   ❤️ 1
    pd.pivot_table(index = "year" , column = "types" , aggfunc=sum)
    试试透视表,效果应该就是你说的这样
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5374 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 07:20 · PVG 15:20 · LAX 00:20 · JFK 03:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.