2016-05-10 199 views
1

比方说,我在熊猫数据帧有数据如下图所示:熊猫查找多层次平均值

enter image description here

我想找到的描述性统计(平均数,中位数,标准开发)的:

    每个队列
  1. 每个队列的唯一用户
  2. 每队列每用户评论
  3. 评论

因此对于输出,我希望看到:每群组

  1. 独立用户 - > [{A:3},{B:2},...],然后找到描述性统计对于系列
  2. 每个用户每个群组评论 - > [{(a,alex):2},{(b,alex):0},{(a,beth):1},{(b,beth) :3} ...]每群组
  3. 评论 - > [{A:5},{b:6} ...]

我使用熊猫,并且我绝对粘在如何做某事 很简单。我正在考虑使用.groupby(),但这并没有产生明确的解决方案。我可以在没有熊猫的情况下做到这一点,但我认为这些是Pandas数据框的一些问题!?

谢谢!

+0

一些示例输出将是有用的。 – piRSquared

+0

增加了我想看到的内容。谢谢! – Alex

+0

请不要用[R]标记python/pands问题,除非有很好的理由。 –

回答

2

解决方案

你可以使用

df.groupby(['Cohort', 'User']).describe() 

df.groupby(['Cohort']).describe() 

根据您所需的输出

df.groupby(['Cohort'])['User'].apply(lambda x: x.describe().ix['unique']) 

df.groupby(['Cohort', 'User'])['Comment'].apply(lambda x: x.describe().ix['unique']) 

df.groupby(['Cohort'])['Comment'].apply(lambda x: x.describe().ix['unique']) 
+0

那些给了我对由'['cohort','user']'分组的数值的描述统计,但我对分组计数本身很感兴趣。感谢您的帮助! – Alex

+0

我认为就是这样!我刚刚添加了'.describe()',并获得了我需要的摘要统计信息。谢谢! – Alex

2
>>> df.groupby('Cohort').User.apply(lambda group: group.unique()) 
Cohort 
a [alex, beth, craig] 
b   [beth, craig] 
Name: User, dtype: object 

>>> df.groupby('Cohort').User.apply(lambda group: group.nunique()) 
Out[40]: 
Cohort 
a 3 
b 2 
Name: User, dtype: int64 

>>> df.groupby(['Cohort', 'User']).Comment.count() 
Out[43]: 
Cohort User 
a  alex  2 
     beth  1 
     craig 2 
b  beth  3 
     craig 3 
Name: Comment, dtype: int64 

df.groupby(['Cohort']).Comment.count() 
Out[44]: 
Cohort 
a 5 
b 6 
Name: Comment, dtype: int64 
+0

感谢此代码。这对于更好地理解正在发生的事情非常有帮助。 – Alex