pandas - 在DataFrame中每个唯一值的列中计算一个值的出现次数

4
假设我有一个类似于下面的DataFrame:
    term      score
0   this          0
1   that          1
2   the other     3
3   something     2
4   anything      1
5   the other     2
6   that          2
7   this          0
8   something     1

我该如何按照term列中的唯一值计算score列中的实例数量?生成类似以下结果:

    term      score 0     score 1     score 2     score 3
0   this            2           0           0           0
1   that            0           1           1           0
2   the other       0           0           1           1
3   something       0           1           1           0
4   anything        0           1           0           0

我已经阅读过的相关问题包括Python Pandas counting and summing specific conditionsCOUNTIF in pandas python over multiple columns with multiple conditions,但似乎都不完全符合我的要求。如this question所提到的pivot_table可能是相关的,但我缺乏经验并且pandas文档简洁难懂。谢谢任何建议。


3
相关:https://dev59.com/d-k5XIcBkEYKwwoY9-hg#47152692 - piRSquared
这是一个非常有用的资源,谢谢。 - Scott Martin
1
欢迎您 (-: - piRSquared
2个回答

7

您也可以使用get_dummiesset_indexsum函数,并带有level参数:

(pd.get_dummies(df.set_index('term'), columns=['score'], prefix_sep=' ')
   .sum(level=0)
   .reset_index())

输出:

        term  score 0  score 1  score 2  score 3
0       this        2        0        0        0
1       that        0        1        1        0
2  the other        0        0        1        1
3  something        0        1        1        0
4   anything        0        1        0        0

1
谢谢,我一直想学习更多关于使用 get_dummies 的内容,这会有所帮助。 - Scott Martin

6

使用groupbysize进行分组,然后通过unstack进行重塑,最后使用add_prefix添加前缀:

df = df.groupby(['term','score']).size().unstack(fill_value=0).add_prefix('score ')

或者使用crosstab

df = pd.crosstab(df['term'],df['score']).add_prefix('score ')

或者使用pivot_table函数:

df = (df.pivot_table(index='term',columns='score', aggfunc='size', fill_value=0)
        .add_prefix('score '))

print (df)
score      score 0  score 1  score 2  score 3
term                                         
anything         0        1        0        0
something        0        1        1        0
that             0        1        1        0
the other        0        0        1        1
this             2        0        0        0

3
我正要发布交叉表,然后你修改了它。然后我想到了数据透视表!你编辑得很好:D。不错的回答。 - ALollz
我认为crosstab是我最喜欢的选项 - 简洁而简单。还要感谢提供了如此多的方法 - 有很多东西可以学习。 - Scott Martin
@jezrael 在你建议使用 aggfunc='size' 的地方,'size' 是什么意思?文档中的示例展示了未加引号的函数传递,例如 aggfunc=np.sum - Scott Martin
1
@ScottMartin - 这个函数与 size 相同。 - jezrael
1
我看到了 - 这是 GroupBy 计算 / 描述性统计函数组 的一部分。谢谢。 - Scott Martin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接