I am currently struggling with the pandas framework.

Let's imagine the following Data Frame:

customer | order_number | product 
A        | O1           | Product_1
A        | O1           | Product_2
A        | O2           | Product_X
B        | O5           | Product_1
C        | O6           | Product_2
C        | 06           | Product_X

What I am trying to do is to count the occurences of "products" based on "order_number". This means that I would like to know how how often e.g. Product_1 and Product_2 were sold within one order. Of course I am interested in every available combination of products. I tried to use df.groupby['order_number'].count() but this is certainly not the data I want. At this point I am not interested in order_numbers nor the customers! Just the available sets of products and how often they appear within the data frame.

Thanks in advance!

Update: Based on my example this explains what I would like to get

Product_1 && Product_2 | One Time
Product_X | One Time
Product_1 | One Time
Product_2 && Product_X | One Time
  • $\begingroup$ this question seems to be a pure programming topic, please refer to other sites like stackoverflow $\endgroup$
    – German C M
    Sep 10, 2020 at 6:47

1 Answer 1


When asking code related questions, its always a good practice to at least provide a sample of the data. Since, you've not given one, I'll create it based on your question.

import pandas as pd

df = pd.DataFrame([('A','01','prod_1'), 
                   ('A','01', 'prod_2'), 
                 columns=['customer', 'ordernum', 'product'])
print (df)
        customer ordernum product
0        A       01  prod_1
1        A       01  prod_2
2        A       02  prod_X
3        B       05  prod_1
4        C       06  prod_2
5        C       06  prod_X

Now, you can use size() or Counter like,

val_count = df.groupby(['product','ordernum']).size()
product  ordernum
prod_1   01          1
         05          1
prod_2   01          1
         06          1
prod_X   02          1
         06          1
dtype: int64

prod_order_count = df.groupby(['product', 'ordernum']).agg(Counter)
product ordernum          
prod_1  01        {'A': 1}
        05        {'B': 1}
prod_2  01        {'A': 1}
        06        {'C': 1}
prod_X  02        {'A': 1}
        06        {'C': 1}
  • $\begingroup$ Thank you for providing the dataframe. Your answer does not answer my question as far as I can tell. Or at least I do not know how to interpret the result? I do not need any grouping by order number. I am interested in the different combinations: How often was prod_1 sold without selling any other products? How often was prod_1 sold together with prod_2 and so on. Do you have any further ideas on how to achieve that? thank you! $\endgroup$
    – caiuspb
    Sep 10, 2020 at 7:40

Not the answer you're looking for? Browse other questions tagged or ask your own question.