根据多个条件pandas计算出现次数?

时间:2017-03-13 10:04:04

标签: python python-2.7 pandas

我有一个名为'table'的数据框:

enter image description here

'type'列有3个类别:1,2和3

如何根据“类型”列的3个类别计算“topic_id”列中每个ID的出现次数,简而言之,每个类别1,2和3出现一个topic_id的次数?

1 个答案:

答案 0 :(得分:1)

我认为你需要crosstab

df = pd.DataFrame({'topic_id':[1,2,3,1,2],
                   'type':[1,2,3,1,2]})

print (df)
   topic_id  type
0         1     1
1         2     2
2         3     3
3         1     1
4         2     2

print (pd.crosstab(df.topic_id, df.type))
type      1  2  3
topic_id         
1         2  0  0
2         0  2  0
3         0  0  1