pandas :使用groupby来获取每个数据类别的均值 [英] Pandas: using groupby to get mean for each data category

查看:216
本文介绍了 pandas :使用groupby来获取每个数据类别的均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的数据框:

I have a dataframe that looks like this:

>>> df[['data','category']]
Out[47]: 
          data     category
  0       4610            2
 15       4610            2
 22       5307            7
 23       5307            7
 25       5307            7
...        ...          ...

数据和类别都是数字,因此我能够做到这一点:

Both data and category are numeric so I'm able to do this:

>>> df[['data','category']].mean()
Out[48]: 
data        5894.677985
category      13.805886
dtype: float64

我正在尝试获取每个类别的均值.它看起来很简单,但是当我这样做时:

And i'm trying to get the mean for each category. It looks straight forward but when I do this:

>>> df[['data','category']].groupby('category').mean()

>>> df.groupby('category')['data'].mean()

它返回如下错误:

DataError: No numeric types to aggregate

如果我将以上两个功能都替换为.count(),则没有错误.

There's no error if I replace both functions above with .count().

我做错了什么?获取每个类别平均值的正确方法是什么?

What do I do wrongly? What's the correct way to get the mean of each category?

推荐答案

可以执行df.dtypes吗?在下面的示例中,输入类型为Int,因为它可以正常工作.

Can you do a df.dtypes ? In the example below type is Int as it works fine.

    import pandas as pd

    ##group by 1 columns
    df = pd.DataFrame({' data': [4610, 4611, 4612, 4613], 'Category': [2, 2,    7, 7]})
    print df.groupby('Category'). mean()


    ##Mutiple columns to group by
    df1 = pd.DataFrame({' data': [4610, 4611, 4612, 4613], 'Category': [2,    2, 7, 7], 'Category2' : ['A','B','A','B']})
    key=['Category','Category2']
    print df1.groupby( key).mean()

 Category Category2       
 2        A           4610
          B           4611
 7        A           4612
          B           4613

这篇关于 pandas :使用groupby来获取每个数据类别的均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆