按两者分组
username
和
prediction
分隔列的相同值
用户名
和
预测
到小组。
prediction 0
和
prediction 1
将被分成不同的组
用户名
. 呼叫
count
每组(注:
我改变了
is_bot
到
预测
在
计数
因为那是你想要的
). 最后,
unstack
把
0
和
1
到列和
rename
你想怎么做就怎么做
df_out = (df.groupby(['username', 'prediction']).prediction.count().unstack(fill_value=0).
rename({0: 'count_human', 1: 'count_bot'}, axis= 1))
Out[30]:
prediction count_human count_bot
username
foo 2 3
foo1 5 2
foo2 0 3
一步一步地:
按每组分组
用户名
和
预测
并指望每一组
零
,
一
每一个
用户名
df.groupby(['username', 'prediction']).prediction.count()
Out[32]:
username prediction
foo 0 2
1 3
foo1 0 5
1 2
foo2 1 3
Name: prediction, dtype: int64
不后退放置索引
预测
到列
df.groupby(['username', 'prediction']).prediction.count().unstack(fill_value=0)
Out[33]:
prediction 0 1
username
foo 2 3
foo1 5 2
foo2 0 3
最后,重命名列以匹配所需的输出
(df.groupby(['username', 'prediction']).prediction.count().unstack(fill_value=0).
rename({0: 'count_human', 1: 'count_bot'}, axis= 1))
Out[34]:
prediction count_human count_bot
username
foo 2 3
foo1 5 2
foo2 0 3