如何汇总大熊猫数据框的所有计数

时间:2020-02-24 12:31:18

标签: python python-3.x pandas

我有一个看起来像这样的熊猫DataFrame(简化示例):

      type   username  product  count
0   access  45michael    63767      1
1   access     7762hc    84325      1
2   access   adrian12   997165      1
3   access   kerrigan   130365      1
4   access      yvera    76863      1
5    order  45michael    76863      1
6    order  45michael    86833      2
7    order  45michael   130365      1
8    order    alicia7   130365      6
9    order     angel8    86217      1
10   order      john5    86833      2
11   order      john5   130365      1
12   order   kerrigan    76863      2

访问权限是指用户检查了产品的文件,而订单是指用户购买了产品 >,我想拥有另一个数据框,可以查看在所有用户中购买了一种产品的多少副本。最后得到这样的东西:

    product count
0    63767  0
1    84325  0
2   997165  0
3   130365  3
4    76863  2
5    86833  2
6    86217  1

1 个答案:

答案 0 :(得分:0)

使用Series.maskSeries.fillnaGroupBy.count

df['count'] = df['count'].mask(df['type'].eq('access'))
dfn = df.groupby('product', sort=False)['count'].count().reset_index()

   product  count
0    63767      0
1    84325      0
2   997165      0
3   130365      3
4    76863      2
5    86833      2
6    86217      1

注意:在这里使用count代替size很重要,因为后者也将算作NaN