我有一个包含 2 个变量的数据框:ID
和 outcome
。我首先尝试 groupby
ID
,然后计算该 ID
中 outcome
的唯一值的数量。
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
但是我需要 yes
和 no
的计数,我该如何实现?谢谢!
最佳答案
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/