Learn Pandas · 10/14

Time Series Data: Working with Dates and Times

4 min read

Working with Time Series Data: Dates and Times in Pandas 🐼

Welcome to the world of time series data! If you've ever looked at stock prices, weather forecasts, or your own heartbeat on a fitness tracker, you've encountered time series data. It's essentially a sequence of data points collected over time. Pandas is an incredibly powerful tool for wrangling and analyzing this kind of data. So, grab a cup of your favorite beverage, and let's get started! ☕️

What's the Big Deal with Time Series Data?

Imagine you have a giant spreadsheet of a company's sales data. If the 'Date' column is just a bunch of text, your computer sees "2023-01-15" and "January 15, 2023" as completely different things. You can't easily ask questions like, "How did sales in January compare to February?" or "What were the sales on all Mondays?". This is where Pandas' time series capabilities come to the rescue. By converting those text-based dates into a format that understands time, you unlock a whole new world of analysis.


1. Converting Strings to Dates: to_datetime()

The Problem: You've imported a dataset, and your date column is being treated as plain old text (an object dtype in Pandas). You can't perform any time-based operations on it. It's like having a calendar where the pages are all jumbled up.

The Solution: The pd.to_datetime() function is your magical spell to convert strings into proper datetime objects.

Let's see it in action. Suppose we have a DataFrame of daily cat video views:

python
import pandas as pd

df = pd.DataFrame({
    'date_str': ['2023-01-01', '2023-01-02', '2023-01-03'],
    'views': [1500, 2200, 1800]
})

print(df.dtypes)

You'll see that date_str is an object. Now, let's work some magic:

python
df['date'] = pd.to_datetime(df['date_str'])
print(df.dtypes)

Voila! You now have a new 'date' column with a datetime64[ns] dtype. Pandas now understands that these are dates.

Fun Fact: The [ns] in datetime64[ns] stands for nanoseconds! Pandas is incredibly precise with time.

to_datetime() is also smart enough to understand many different date formats.

python
pd.to_datetime('Jan 15, 2024')
pd.to_datetime('2024/01/15')
pd.to_datetime('15-01-2024', dayfirst=True) # Important for non-US date formats!

If you have a weird date format, you can even provide a format string to help Pandas out:

python
pd.to_datetime('2024-31-01', format='%Y-%d-%m')

2. Setting Up: Using Datetime as the DataFrame Index

The Problem: Even with a datetime column, selecting data for specific time periods can be a bit clunky. You might find yourself writing complex filtering conditions.

The Solution: Set your datetime column as the DataFrame's index! This turns your DataFrame into a time-series-aware powerhouse.

python
df = df.set_index('date')
print(df.head())

Now, your DataFrame's index is no longer boring old numbers (0, 1, 2...). It's a DatetimeIndex.

Why is this so cool? You can now slice and dice your data with time-based precision:

python
# Get data for a specific day
df.loc['2023-01-02']

# Get data for a range of dates
df.loc['2023-01-01':'2023-01-02']

This makes your code much more readable and intuitive.


3. Changing Frequencies: Resampling Time Series Data

The Problem: Your data is recorded every hour, but you need to see the total daily views. Or maybe you have daily data and you want to see the average monthly views. You need to change the time frequency of your data.

The Solution: The resample() method is your go-to for this. It's like a time machine for your data's frequency.

Let's imagine our cat video data is now hourly:

python
# Create a sample hourly DataFrame
rng = pd.date_range('2023-01-01', periods=100, freq='H')
ts = pd.Series(range(100), index=rng)
df_hourly = pd.DataFrame({'views': ts})

# Resample to daily and get the sum of views
daily_views = df_hourly.resample('D').sum()
print(daily_views.head())

Here, 'D' is an offset alias for "day." There are many of these for different frequencies like 'W' (weekly), 'M' (monthly), 'Q' (quarterly), and 'A' (annually).

You can also use other aggregation functions like mean(), min(), max(), and ohlc() (open-high-low-close, popular in finance).

This process of converting to a lower frequency (e.g., hourly to daily) is called downsampling. The reverse, going from a lower to a higher frequency, is called upsampling.


4. Smoothing Data: Rolling Windows and Moving Averages

The Problem: Your data is very noisy. For example, daily sales figures might jump up and down a lot. You want to see the underlying trend more clearly.

The Solution: Rolling windows to the rescue! This technique involves calculating a statistic, like an average, over a sliding window of time.

The most common use of this is to calculate a moving average. Let's go back to our daily cat video views:

python
df['3-day_moving_avg'] = df['views'].rolling(window=3).mean()
print(df)

Here's what's happening under the hood:

  • For '2023-01-01', there aren't 3 days of data yet, so the result is NaN.
  • For '2023-01-02', still not 3 days, so NaN.
  • For '2023-01-03', it takes the views from Jan 1, 2, and 3, and calculates the average.
  • For '2023-01-04', it takes the views from Jan 2, 3, and 4, and so on.

You'll notice the first few values are NaN (Not a Number). This is because the window doesn't have enough data points at the beginning. You can control this with the min_periods parameter.

Rolling windows are fantastic for smoothing out short-term fluctuations and highlighting longer-term trends.


For the Curious 🧐

Challenge

You are provided with a Pandas DataFrame sales_df that contains transactional sales data. The timestamp column, crucial for analysis, is currently stored as a string (object) dtype in a non-standard month-day-Year Hour:Minute format.

Your goal is to process this data to analyze daily sales trends.

Tasks:

  1. Convert the timestamp column in sales_df from string objects to proper datetime objects. You will need to specify the exact format of the date strings for the conversion function.
  2. Transform the DataFrame by setting the newly converted timestamp column as its index, making it a time-series DataFrame.
  3. Create a new DataFrame called daily_analysis by downsampling the original data. This new DataFrame should aggregate sales to a daily frequency by summing them up. The resulting aggregated column must be named total_sales.
  4. Calculate the 3-day moving average to identify the underlying sales trend. Add a new column to your daily_analysis DataFrame named 3_day_moving_avg that contains this calculation based on the total_sales.

Expected result

The final variable daily_analysis should be a Pandas DataFrame that meets the following criteria:

  • Its index must be a DatetimeIndex with daily frequency, ranging from 2023-01-01 to 2023-01-10.
  • It must contain exactly two columns: total_sales and 3_day_moving_avg.
  • The total_sales column should contain the sum of all sales for that day (e.g., for 2023-01-01, the value should be 370).
  • The 3_day_moving_avg column should contain the rolling 3-day average of total_sales. The first two values in this column are expected to be NaN since there isn't enough preceding data to compute the average.
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.