Pandas Groupby:数量和平均值相结合

Lew*_*son 18 python group-by dataframe python-2.7 pandas

与PANDAS合作,尝试将数据框汇总为某些类别的计数,以及这些类别的均值情绪分数.

有完整的字符串表有不同的情绪分数,我想通过说出他们有多少帖子以及这些帖子的平均情绪来对每个文本来源进行分组.

我的(简化)数据框如下所示:

source    text              sent
--------------------------------
bar       some string       0.13
foo       alt string        -0.8
bar       another str       0.7
foo       some text         -0.2
foo       more text         -0.5
Run Code Online (Sandbox Code Playgroud)

这个输出应该是这样的:

source    count     mean_sent
-----------------------------
foo       3         -0.5
bar       2         0.415
Run Code Online (Sandbox Code Playgroud)

答案在某处:

df['sent'].groupby(df['source']).mean()
Run Code Online (Sandbox Code Playgroud)

然而,只给出每个来源,它的意思是,没有列标题.

提前致谢!

jez*_*ael 19

你可以用groupbyaggregate:

df = df.groupby('source') \
       .agg({'text':'size', 'sent':'mean'}) \
       .rename(columns={'text':'count','sent':'mean_sent'}) \
       .reset_index()
print (df)
  source  count  mean_sent
0    bar      2      0.415
1    foo      3     -0.500
Run Code Online (Sandbox Code Playgroud)

  • 好答案。如果您想对同一列的计数和均值怎么做?如果您两次输入列名,则会得到重复的键错误。 (2认同)
  • @Yu Chen当然,请使用'df1 =(df.groupby('source')['your column'] .agg(('count','size'),('avg','mean')).reset_index( ))` (2认同)
  • 我想要数据集中的几个变量的平均值,并且我只想要分组所依据的变量的计数。有没有办法做到这一点? (2认同)

nev*_*ves 18

在较新版本的 Panda 中,您不再需要重命名,只需使用命名参数:

df = df.groupby('source') \
       .agg(count=('text', 'size'), mean_sent=('sent', 'mean')) \
       .reset_index()

print (df)
  source  count  mean_sent
0    bar      2      0.415
1    foo      3     -0.500
Run Code Online (Sandbox Code Playgroud)


小智 6

下面一个应该可以正常工作:

df[['source','sent']].groupby('source').agg(['count','mean'])
Run Code Online (Sandbox Code Playgroud)