Skip to content
Advertisement

How to count the number of times a combination appears in a binary table in Python?

I need to create a Pandas DataFrame that contains two columns:

  1. Combination – contains tuples that describe a combination of products in the binary table (e.g., (“bread”, “eggs”))
  2. Count – contains the number of times that this combination appeared in the binary table

The binary table that I keep referring to looks like this. 1 just means that the product is in that specific product (or in this case, it is present in the combination), and 0 if otherwise.

JavaScript

I already figured out how to create the combinations column, I just don’t know how to create the count column using the data from the binary table. Here’s my code so far:

JavaScript

This is what the code looks like but I still need to add the count column.

JavaScript

Can anyone please help me? Thank you!

Advertisement

Answer

Here is one solution:

JavaScript

For the visible part of your df (the rows you provided in the question) this code returns:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement