Search⌘ K
AI Features

Challenge 1: Count of Dates in Month (Trivial)

Explore how to manipulate and filter date data in Pandas to count specific monthly entries. This lesson teaches casting date columns to datetime types and filtering by month to extract targeted information such as concert counts in September 2019 and 2020.

Problem definition

Your music analyst now has a list of date entries, where every entry is the date when a concert of their favorite band was held.

The analyst now wants to know the total number of concerts held in the month of September in 2019 and 2020.

Expected output

A single int representing the aforementioned count

Example: 7

Challenge

Python 3.5
import pandas as pd
def test():
df = pd.read_csv('dates.csv')
pass

Solution

Python 3.5
import pandas as pd
def test():
df = pd.read_csv('dates.csv')
df['date'] = df['date'].map(lambda x: pd.to_datetime(x))
df['month'] = df['date'].dt.month
return len(df[df['month']==9])
print(test())

Solution explanation

The first step to manipulate dates is to cast the date column as a datetime type. There are several different ways to do this. The one shown above is using the map function on the date column.

Different levels of granularity can be achieved to extract date properties from the newly created datetime column. Here, you are interested in month information, so you use the accessor .dt.month to create a new column.

The last step is a very basic filter to get the length of the DataFrame that was a month value of 9 (September).