Skip to content

Vending Machines Problem


You own a collection of vending machines, and you want to evaluate your inventory. Given a DataFrame of (machine, product, stock), determine the number of machines carrying each product and how many of them are out of stock.

import numpy as np
import pandas as pd

machine_products = pd.DataFrame({
    'machine': ['abc', 'abc', 'def', 'def', 'def', 'ghi'],
    'product': ['skittles', 'soap', 'soap', 'm&ms', 'skittles', 'm&ms'],
    'stock': [10, 0, 15, 2, 0, 3]
})
print(machine_products)
#   machine   product  stock
# 0     abc  skittles     10
# 1     abc      soap      0
# 2     def      soap     15
# 3     def      m&ms      2
# 4     def  skittles      0
# 5     ghi      m&ms      3

Build a new DataFrame with product as the row index, and calculated columns n_machines and n_machines_empty.


Try with Google Colab