将groupby应用于pandas datarame时添加Counters对象

白色159

我试图将words_count列按两者进行分组essay_Setdomain1_score并添加计数器words_count以添加计数器结果,如下所示:

>>> c = Counter(a=3, b=1)
>>> d = Counter(a=1, b=2)
>>> c + d                       # add two counters together:  c[x] + d[x]
Counter({'a': 4, 'b': 3})

我使用以下命令将它们分组:words_freq_by_set = words_freq_by_set.groupby(by=["essay_set", "domain1_score"])但不知道如何通过Counter加法函数将其应用于words_count简单的列+这是我的数据框:

在此处输入图片说明

cs95

GroupBy.sum与Counter对象一起使用。但是,我应该提到这个过程是成对的,所以这可能不是很快。我们试试吧

words_freq_by_set.groupby(by=["essay_set", "domain1_score"])['words_count'].sum()

df = pd.DataFrame({
    'a': [1, 1, 2], 
    'b': [Counter([1, 2]), Counter([1, 3]), Counter([2, 3])]
})
df

   a             b
0  1  {1: 1, 2: 1}
1  1  {1: 1, 3: 1}
2  2  {2: 1, 3: 1}


df.groupby(by=['a'])['b'].sum()

a
1    {1: 2, 2: 1, 3: 1}
2          {2: 1, 3: 1}
Name: b, dtype: object

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章