python - 分组并计算唯一值的数量( Pandas )

标签 python pandas dataframe count unique

我有一个包含 2 个变量的数据框:IDoutcome。我首先尝试 groupby ID,然后计算该 IDoutcome 的唯一值的数量。

df
ID    outcome
1      yes
1      yes
1      yes
2      no
2      yes
2      no

预期输出:

ID    yes    no
1      3     0
2      1     2

我的代码df[['PID', 'outcome']].groupby('PID')['outcome'].nunique()给出了唯一值本身的个数,比如那:

ID
1   2
2   2

但是我需要 yesno 的计数,我该如何实现?谢谢!

最佳答案

pd.crosstab怎么样? ?

In [1217]: pd.crosstab(df.ID, df.outcome)
Out[1217]: 
outcome  no  yes
ID              
1         0    3
2         2    1

关于python - 分组并计算唯一值的数量( Pandas ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45495153/

相关文章:

xml - R:将 XML 数据转换为数据框

Python 数据框 : cumulative sum of column until condition is reached and return the index

python - 是时候在 Python 中给变量赋值了

python - 在一台 Xampp Windows Apache Mod_WSGI 服务器上部署两个 Django 项目

python - 如何从 Python 列表中删除重复的字典(带有嵌套的字典)?

python - 在 Python 中,我需要执行一个访问前一个 "grouped value"的迭代 groupby 来建立聚合列的行的值

python - 导入错误:没有名为 'dlib' 的模块

python - Pandas :找到每个人最常见的字符串

python - 如何将嵌套 JSON 转换为 CSV

python - Pandas 根据列中的最小值到最大值对行重新排序