【发布时间】:2019-08-02 09:31:46
【问题描述】:
我有这个数据框:
test = pd.DataFrame({
'user': [1,2,3,4,5,6,7,8,9],
'category1': [2,4,0,9,1,4,6,0,1],
'category2': [1,0,1,3,2,0,0,9,0],
'topic1': [3,2,1,4,2,0,0,1,2],
'topic2': [0,0,7,2,1,4,6,0,0],
})
user category1 category2 topic1 topic2
0 1 2 1 3 0
1 2 4 0 2 0
2 3 0 1 1 7
3 4 9 3 4 2
4 5 1 2 2 1
5 6 4 0 0 4
6 7 6 0 0 6
7 8 0 9 1 0
8 9 1 0 2 0
它显示了用户访问不同类别和不同主题的次数。
我需要计算访问过某个类别的用户也访问过某个主题的次数。所以输出应该是这样的:
category category_count topic topic_count
0 category1 27 topic1 13
1 category1 27 topic2 13
2 category2 16 topic1 11
3 category2 16 topic2 10
感谢您的帮助!
UPD:
我最终想出了这个解决方案,但我仍然认为应该有一个更优雅的方式......
categories = ['category1', 'category2']
topics = ['topic1', 'topic2']
l1 = []
l2 = []
l3 = []
l4 = []
for c in categories:
for t in topics:
l1.append(c)
l2.append(test[c].sum())
l3.append(t)
l4.append(test[test[c] > 0][t].sum())
d = {'category':l1,
'category_count':l2,
'topic':l3,
'topic_count':l4}
test_new = pd.DataFrame(d)
test_new
【问题讨论】:
-
topic1应该是 15.. 不是吗?为什么要重复类别和主题的类型? -
test.groupby('category1').topic1.sum()?
标签: python-3.x pandas group-by transpose