如何按对象计算 pandas 组列中的不同值? [英] How to count distinct values in a column of a pandas group by object?

查看:25
本文介绍了如何按对象计算 pandas 组列中的不同值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Pandas 数据框并将其按两列分组(例如 col1col2).对于 col1col2 的固定值(即对于一个组),我可以在 col3 中有几个不同的值.我想计算第三列中不同值的数量.

I have a pandas data frame and group it by two columns (for example col1 and col2). For fixed values of col1 and col2 (i.e. for a group) I can have several different values in the col3. I would like to count the number of distinct values from the third columns.

例如,如果我将其作为输入:

For example, If I have this as my input:

1  1  1
1  1  1
1  1  2
1  2  3
1  2  3
1  2  3
2  1  1
2  1  2
2  1  3
2  2  3
2  2  3
2  2  3

我想将此表(数据框)作为输出:

I would like to have this table (data frame) as the output:

1  1  2
1  2  1
2  1  3
2  2  1

推荐答案

df.groupby(['col1','col2'])['col3'].nunique().reset_index()

这篇关于如何按对象计算 pandas 组列中的不同值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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