Contents

Python Pandas For Your Grandpa - 3.12 Challenge: Vending Machines

Setup

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. In other words, build a new DataFrame with product as the row index, and calculated columns n_machines and n_machines_empty.

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

Solution

def count_zero(x): return (x == 0).sum()
machine_products.groupby('product').agg(
    n_machines = ('stock', 'count'),
    n_machines_empty = ('stock', count_zero)
)
##           n_machines  n_machines_empty
## product                               
## m&ms               2                 0
## skittles           2                 1
## soap               2                 1

Course Curriculum

  1. Introduction
    1.1 Introduction
  2. Series
    2.1 Series Creation
    2.2 Series Basic Indexing
    2.3 Series Basic Operations
    2.4 Series Boolean Indexing
    2.5 Series Missing Values
    2.6 Series Vectorization
    2.7 Series apply()
    2.8 Series View vs Copy
    2.9 Challenge: Baby Names
    2.10 Challenge: Bees Knees
    2.11 Challenge: Car Shopping
    2.12 Challenge: Price Gouging
    2.13 Challenge: Fair Teams
  3. DataFrame
    3.1 DataFrame Creation
    3.2 DataFrame To And From CSV
    3.3 DataFrame Basic Indexing
    3.4 DataFrame Basic Operations
    3.5 DataFrame apply()
    3.6 DataFrame View vs Copy
    3.7 DataFrame merge()
    3.8 DataFrame Aggregation
    3.9 DataFrame groupby()
    3.10 Challenge: Hobbies
    3.11 Challenge: Party Time
    3.12 Challenge: Vending Machines
    3.13 Challenge: Cradle Robbers
    3.14 Challenge: Pot Holes
  4. Advanced
    4.1 Strings
    4.2 Dates And Times
    4.3 Categoricals
    4.4 MultiIndex
    4.5 DataFrame Reshaping
    4.6 Challenge: Class Transitions
    4.7 Challenge: Rose Thorn
    4.8 Challenge: Product Volumes
    4.9 Challenge: Session Groups
    4.10 Challenge: OB-GYM
  5. Final Boss
    5.1 Challenge: COVID Tracing
    5.2 Challenge: Pickle
    5.3 Challenge: TV Commercials
    5.4 Challenge: Family IQ
    5.5 Challenge: Concerts

Additional Content

  1. Python NumPy For Your Grandma
  2. Neural Networks For Your Dog
  3. Introduction To Google Colab