【问题标题】:pandas - Counting occurrences of a value in a DataFrame per each unique value in another columnpandas - 根据另一列中的每个唯一值计算 DataFrame 中某个值的出现次数
【发布时间】:2018-09-20 14:05:12
【问题描述】:

假设我有一个 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 文档的简洁性,我受到了阻碍。感谢您的任何建议。

【问题讨论】:

标签: python pandas dataframe pivot-table


【解决方案1】:

您还可以使用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

【讨论】:

  • 谢谢你,get_dummies 是我一直想要了解更多关于使用的东西,这将对此有所帮助。
【解决方案2】:

使用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

【讨论】:

  • 我正要发布交叉表,然后你编辑了。然后我想,哦,枢轴!你编辑了:D。不错的答案
  • 我认为crosstab 是我最喜欢的选项 - 简洁明了。还要感谢您提供的各种方法 - 需要学习很多东西。
  • @jezrael 你在哪里建议aggfunc='size',什么是'size'?文档中的示例显示了不带引号传递的函数,例如 aggfunc=np.sum
  • @ScottMartin - 这个功能和size一样
  • 我明白了 - GroupBy computations / descriptive stats function group 的一部分。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-12
  • 1970-01-01
  • 2019-12-08
  • 1970-01-01
  • 1970-01-01
  • 2012-10-25
  • 2021-08-26
相关资源
最近更新 更多