Contents

Python Pandas For Your Grandpa - 3.11 Challenge: Party Time

Setup

Whenever your friends John and Judy visit you together, y’all have a party. Given a DataFrame with 10 rows representing the next 10 days of your schedule and whether John and Judy are scheduled to make an appearance, insert a new column called days_til_party that indicates how many days until the next party relative to each day.

days_til_party should be 0 on days where a party is occurs, 1 on days where a party doesn’t occur but will occur the next day, etc.

import numpy as np
import pandas as pd

generator = np.random.default_rng(123)
df = pd.DataFrame({
    'john': generator.choice([True, False], size=10, replace=True),
    'judy': generator.choice([True, False], size=10, replace=True)
})
print(df)
##     john   judy
## 0   True   True
## 1  False  False
## 2  False   True
## 3   True  False
## 4  False   True
## 5   True   True
## 6   True  False
## 7   True  False
## 8   True  False
## 9   True  False

Solution

party = df.john & df.judy
grps = party.iloc[::-1].cumsum()
df['days_til_party'] = party.groupby(grps).cumcount(ascending=False)
df.loc[(party.loc[party].index[-1] + 1):, 'days_til_party'] = pd.NA
print(df)
##     john   judy days_til_party
## 0   True   True              0
## 1  False  False              4
## 2  False   True              3
## 3   True  False              2
## 4  False   True              1
## 5   True   True              0
## 6   True  False           <NA>
## 7   True  False           <NA>
## 8   True  False           <NA>
## 9   True  False           <NA>

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