Python:如何在不聚合数据帧的情况下进行分组和计数

标签 python pandas dataframe pandas-groupby

我的数据框如下所示:

enter image description here

现在我想按列['name', 'grade']分组,并执行count(),结果如下所示:

df.groupby(['姓名', '成绩'], as_index=False).count()

enter image description here

但我想要的应该是这样的:

enter image description here

最佳答案

尝试使用转换:

dict = {"year": [2010, 2011, 2012, 2010, 2011],
   "name": ["kelly", "kelly", "kelly", "peter", "peter"],
   "grade": ["A", "A", "C", "B", "B"] }

import pandas as pd
df = pd.DataFrame(dict)
print(df)

grp = df.groupby(['name', 'grade'], as_index=False)
print(grp.count())

df['count'] = grp['year'].transform('count')
print(df)

PS:记入https://stackoverflow.com/a/41925722/1681985

关于Python:如何在不聚合数据帧的情况下进行分组和计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59486029/

相关文章:

Python Pandas 多处理应用

python - Python 中的返回值

python - 使用 pandas 时的异常处理 apply

r - 将列添加到数据框中,在另一列中测试分类变量

python - 仅下载某些 MNIST 数字

python - wxpython 应用程序中严重的内存泄漏

python - 有效地将数据从 CSV 读取到具有多个分隔符的数据框中

python - 使用 pandas 使用通配符对列名称进行排序

python - 单例数组 array(<function train at 0x7f3a311320d0>, dtype=object) 不能被视为有效集合

pandas - 如何通过每行的第一个单词将 pandas 中的行汇总为该第一个单词的聚合?