寻找多层次平均值

2024-04-27 16:16:28 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我在熊猫数据框中有如下数据:

enter image description here

我想找到以下描述性统计数据(平均值、中位数、标准偏差):

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

所以对于输出,我希望看到:

  1. 每个群组的唯一用户数->[{a:3},{b:2},…]然后找到序列的描述性统计
  2. 每个群组每个用户的评论->[{(a、 亚历克斯:2},{(b,亚历克斯):0},{(a,贝丝):1},{(b,贝丝):3}……]
  3. 每个群组的评论->[{a:5},{b:6}…]

我用的是熊猫,我完全不知道怎么做这么简单的事。我曾考虑过使用.groupby(),但没有给出一个明确的解决方案。我可以在没有熊猫的情况下做到这一点,但我认为熊猫数据框就是为这些问题而设计的

谢谢


Tags: 数据用户gt队列评论序列解决方案统计数据
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'])
>>> 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

相关问题 更多 >