Pandas Groupby:计数和平均合并



与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

这样的输出应该是这样的:

source    count     mean_sent
-----------------------------
foo       3         -0.5
bar       2         0.415

答案沿着:

的线
df['sent'].groupby(df['source']).mean()

但只给出了每个源,这是均值,没有列标题。

您可以将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

在较新版本的pandas中,您不再需要重命名,只需使用名为contregation:

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

下面的工作正常:

df[['source','sent']].groupby('source').agg(['count','mean'])

实现此目的的较短版本是:

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

这样做的好处是,如果您要拿多个变量的平均值,但只计数一次,则可以扩展它。在这种情况下,您将必须通过字典:

df.groupby('source')['sent1', 'sent2'].agg({'count': 'size', 'means': 'mean'}).reset_index()

对于那些正在寻找两个以上列的聚合的人(如我所在):只需将它们添加到'agg'中。

df = df.groupby(['id']).agg({'texts': 'size', 'char_num': 'mean', 'bytes': 'mean'}).reset_index()

我认为这应该提供您想要的输出:

result = pd.DataFrame(df.groupby('source').size())
results['mean_score'] =  df.groupby('source').sent.mean()

最新更新