pandas 计数唯一行 [英] Pandas Counting Unique Rows

查看:90
本文介绍了 pandas 计数唯一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似于的熊猫数据框:

I have a pandas data frame similar to:

ColA ColB
1    1
1    1
1    1
1    2
1    2
2    1
3    2

我希望输出的功能与计数器.我需要知道每行显示多少次(所有列都相同.

I want an output that has the same function as Counter. I need to know how many time each row appears (with all of the columns being the same.

在这种情况下,正确的输出将是:

In this case the proper output would be:

ColA ColB Count
1    1    3
1    2    2
2    1    1
3    2    1

我尝试了某种方式:

df.groupby(['ColA','ColB']).ColA.count()

但这给我带来了一些丑陋的输出,我在格式化时遇到了困难

but this gives me some ugly output I am having trouble formatting

推荐答案

您可以使用 reset_index :

You can use size with reset_index:

print df.groupby(['ColA','ColB']).size().reset_index(name='Count')
   ColA  ColB  Count
0     1     1      3
1     1     2      2
2     2     1      1
3     3     2      1

这篇关于 pandas 计数唯一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆