2024-04-25 07:39:17 发布
网友
{and{data2}有groupbyID,并计算outcome中outcome的唯一值的数目。在
ID
outcome
df ID outcome 1 yes 1 yes 1 yes 2 no 2 yes 2 no
预期产量:
我的代码df[['PID', 'outcome']].groupby('PID')['outcome'].nunique()给出了唯一值本身的编号,这样:
df[['PID', 'outcome']].groupby('PID')['outcome'].nunique()
ID 1 2 2 2
但是我需要yes和no的计数,我怎样才能做到呢?谢谢!在
yes
no
选项2pd.factorize+np.bincount 这是复杂而痛苦的。。。但速度很快。在
pd.factorize
np.bincount
fi, ui = pd.factorize(df.ID.values) fo, uo = pd.factorize(df.outcome.values) n, m = ui.size, uo.size pd.DataFrame( np.bincount(fi * m + fo, minlength=n * m).reshape(n, m), pd.Index(ui, name='ID'), pd.Index(uo, name='outcome') ) outcome yes no ID 1 3 0 2 1 2
选项C
方案四。在
df.groupby(['ID', 'outcome']).size().unstack(fill_value=0)
^{}怎么样?在
In [1217]: pd.crosstab(df.ID, df.outcome) Out[1217]: outcome no yes ID 1 0 3 2 2 1
在ID列上分组,然后在outcome列上使用value_counts进行聚合。这将产生一个序列,因此需要使用.to_frame()将其转换回一个数据帧,以便可以取消对yes/no的堆栈(即将它们作为列)。然后用零填充空值。在
value_counts
.to_frame()
df_total = df.groupby('ID')['outcome'].value_counts().to_frame().unstack(fill_value=0) df_total.columns = df_total.columns.droplevel() >>> df_total outcome no yes ID 1 0 3 2 2 1
选项2
pd.factorize
+np.bincount
这是复杂而痛苦的。。。但速度很快。在
选项C
^{pr2}$方案四。在
^{} 怎么样?在
在
ID
列上分组,然后在outcome
列上使用value_counts
进行聚合。这将产生一个序列,因此需要使用.to_frame()
将其转换回一个数据帧,以便可以取消对yes/no的堆栈(即将它们作为列)。然后用零填充空值。在相关问题 更多 >
编程相关推荐