python - pandas - 根据另一列中的每个唯一值计算 DataFrame 中某个值的出现次数

标签 python pandas dataframe pivot-table

假设我有一个 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 ,但似乎都不是我想要做的。 pivot_tablethis question 所述似乎它可能是相关的,但我因缺乏经验和 pandas 文档的简洁性而受阻。感谢您的任何建议。

最佳答案

您还可以将 get_dummiesset_indexsumlevel 参数一起使用:

(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/

相关文章:

python - 对 pandas 数据框进行哈希计算以进行计算列缓存

python - 将 pandas 数据帧转换为 json 或 dict,然后返回到具有非唯一列的 df

python - 按日期统计组数

python - 使pycaffe fatal error : 'Python.h' file not found

python - 如何使用 R 获取过去几年的高音扬声器数据?

python - 识别并计算数据框中前 x 个对象的统计信息

python - 类型推断 : df. append() 与 df.loc[]

python - 使用 IPython Notebook 获取输出

python - inet_aton 类似 IPv6 的功能

python - 将变量存储为另一个变量的属性是个好习惯吗?