python - 如何计算每个季节有多少天的答案等于 pandas 数据框中的不同数字?

标签 python pandas count

我在 pandas df 中有以下数据:

   Season | Answer 
   ------ | ------
0    4    | 0
1    4    | 0
2    2    | 0
3    1    | 1
4    4    | 1
5    2    | 1
6    3    | 0
7    1    | 0.5
8    4    | 1
9    4    | 0   

我想计算每个季节有多少天有answer=1,有多少天有answer=0.5,有多少天有answer=0以获得下一个结果:

   Season | Answer | Quantity 
   ------ | ------ | --------
0    4    | 0      | 3
1    4    | 0      | 3
2    2    | 0      | 1
3    1    | 1      | 1
4    4    | 1      | 2
5    2    | 1      | 1
6    3    | 0      | 1
7    1    | 0.5    | 1
8    4    | 1      | 2
9    4    | 0      | 3

最佳答案

让我们尝试使用 groupbytransfrom:

df['Quantity'] = df.groupby(['Season','Answer'])['Answer'].transform('size')

输出:

   Season  Answer  Quantity
0       4     0.0       3.0
1       4     0.0       3.0
2       2     0.0       1.0
3       1     1.0       1.0
4       4     1.0       2.0
5       2     1.0       1.0
6       3     0.0       1.0
7       1     0.5       1.0
8       4     1.0       2.0
9       4     0.0       3.0

关于python - 如何计算每个季节有多少天的答案等于 pandas 数据框中的不同数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45083091/

相关文章:

子查询中的 MySQL COUNT 行

statistics - 为什么Wemf和Google Analytics(分析)告诉我那么不同?

MySQL 如何在左连接中计算 where 子句仅用于计数?

python - 尝试理解精简的Python

python - 将列表中的项目添加到python中的列表列表

Python 队列 block 超时不会超时 - 知道为什么吗?

python - groupby 和mean返回NaN

python - PyGithub - 尝试更改默认分支时无法设置属性错误

python - Pandas 将数据框中的多个多索引列乘以另一列

Python Pandas : change only next unnamed column with the previous column name