假设我有一个 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 conditions和 COUNTIF in pandas python over multiple columns with multiple conditions ,但似乎都不是我想要做的。 pivot_table
如 this question 所述似乎它可能是相关的,但我因缺乏经验和 pandas 文档的简洁性而受阻。感谢您的任何建议。
最佳答案
您还可以将 get_dummies
、set_index
和 sum
与 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
关于python - pandas - 根据另一列中的每个唯一值计算 DataFrame 中某个值的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52427024/