计算与熊猫分组的总数

时间:2020-11-11 09:09:13

标签: python pandas pandas-groupby

details = { 
    'order_number' : ['#1', '#2', '#3', '#4','#4'], 
    'disc_code' : ['no_discount', 'superman', 'hero', 'numero_uno','numero_uno'], 
    }
df = pd.DataFrame(details)

len(df)-> 6408
每行归因于一种产品,而不是一项事务。 如果我将每行分组到每个订单名称,则有3560行。 len(df.groupby('order_number'))-> 3560

我要计算总共使用了多少个折扣代码。 (如果未使用折扣代码,则值为'no_discount')

在SQL中,语法可能看起来像这样:

SELECT COUNT(*)
FROM transactions
GROUP BY order_number
WHERE discount_code != 'no_discount' 

1 个答案:

答案 0 :(得分:0)

如果需要按order_number计算,请将boolean indexingGroupBy.size一起使用:

df1 = (df[df['disc_code'].ne('no_discount')]
           .groupby('order_number')
           .size()
           .reset_index(name='count'))
print (df1)
  order_number  count
0           #2      1
1           #3      1
2           #4      2

如果需要计数,则所有值仅按条件计数True的值,以不等于Series.nesum

out = df['disc_code'].ne('no_discount').sum()