python - Pandas 按多列和值级别进行分组并将结果附加到原始数据框

标签 python pandas group-by

我有一个数据框,想按几列和不同级别的值对其进行分组。另外,我想将分组结果附加到原始数据框中。

这是原始数据框:

  AAA BBB CCC 
  x1  y1  yes 
  x1  y1  yes  
  x1  y1  no   
  x1  y2  no
  x2  y2  yes
  x2  y2  no 

这就是我想要的:

  AAA BBB CCC Yes No
  x1  y1  yes 2   1  
  x1  y1  yes 2   1
  x1  y1  no  2   1
  x1  y2  no  0   1
  x2  y2  yes 1   1
  x2  y2  no  1   1

这里的想法是,我想按 AAA 和 BBB 进行分组,并在 CCC 中为每个组计算是/否。然后,我想将计数值添加到 2 个新列"is"和“否”中。

提前致谢!

最佳答案

一种方法是:

  • AAABBB 分组
  • 获取每个组的CCCvalue_counts()
  • 将最里面的值计数索引(由 yesno 组成)解压到列中
  • 将计数与原始 DataFrame 合并

counts = (df.groupby(['AAA', 'BBB'])['CCC']
            .value_counts()
            .unstack()
            .fillna(0)
            .astype(int))

counts.columns = counts.columns.str.title()

pd.merge(df, counts, left_on=['AAA', 'BBB'], right_index=True)

  AAA BBB  CCC  No  Yes
0  x1  y1  yes   1    2
1  x1  y1  yes   1    2
2  x1  y1   no   1    2
3  x1  y2   no   1    0
4  x2  y2  yes   1    1
5  x2  y2   no   1    1

关于python - Pandas 按多列和值级别进行分组并将结果附加到原始数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57128046/

相关文章:

python - Matplotlib "ValueError: x and y must be the same size"

python - Pandas 用两个不同的 ID 压平数据框?

python - 用所有缺失的数据组合填充 list/pandas.dataframe(如 R 中的 complete())

php - MySQL 查询中的组逗号分隔元素

python - 为什么我的 PyGame 平台游戏突然变慢了?

python - 无法在 AWS Elastic Beanstalk 上找到 Django 应用程序的模块

python - 从一个数据框中删除另一个数据框的列中的元素

mysql - 选择 MAX(ID) mysql

mysql - 如何对后续行进行分组(基于条件)然后对它们进行计数[MySQL]?

python - 如何更正我的朴素贝叶斯方法返回极小的条件概率?