Time-Series Data Manipulation with Pandas
Working with time series in pandas, using YouTube publish data as the example: parse the timestamp column into datetimes, set it as the index, filter by date, resample to a period that makes sense, and calculate a simple moving average over the result. The same moving average works on stock prices.
Check the date column
pandas only treats a column as dates once it has the datetime type, so checking the types comes first. The dataset contains the video title, the publish time and the total views of my YouTube videos.
The info method shows that “Video publish time” has missing values and is stored as text (“object”; pandas 3 shows it as “str”). Text is no use for time-series work, so the column has to become a datetime. If you are new to pandas, my complete pandas tutorial covers importing pandas and loading data step by step.
import pandas as pd
# load the data
df = pd.read_csv(
"https://raw.githubusercontent.com/Sven-Bo/datasets/master/YouTube_Data.csv",
usecols=["Video title", "Video publish time", "Views"],
)
df.sample(5)
# get a quick overview of the data
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 107 entries, 0 to 106
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Video title 107 non-null object
1 Video publish time 102 non-null object
2 Views 107 non-null int64
dtypes: int64(1), object(2)
memory usage: 2.6+ KB
Clean and index the data
The cleaning step drops the five rows without a publish time, adds a “date” column converted with pd.to_datetime, makes it the index and sorts it. Method chaining keeps these steps in one readable block that is easy to debug line by line.
# clean the dataframe
(df
.dropna()
.assign(date=pd.to_datetime(df["Video publish time"]))
.set_index("date")
.sort_index()
).head()
Video title Video publish time Views
date
2020-07-05 📈 How To Get Stock Data In Excel By Using VBA | Step-by-Step Tutorial 5-Jul-20 23304
2020-07-18 💻 How To Create A GUI In Python Using Tkinter To Display COVID19 Stats | Step-by-Step Tutorial 18-Jul-20 3058
2020-07-25 How To Create An Interactive Gantt Diagram In Python Using Plotly & Excel | Step-by-Step Tutorial 25-Jul-20 15731
2020-07-27 How To Execute A Python Script From Excel Using VBA | Step-by-Step Tutorial [EASY] 27-Jul-20 42471
2020-08-02 How To Create A Treemap & Sunburst Chart In Python Using Plotly & Excel | Tutorial [EASY] 💻 2-Aug-20 6604
Wrapped in a function, the same chain gives a clean DataFrame to work with:
# convert the cleaning process into a function
def clean_data(df):
return (
df.dropna()
.assign(date=pd.to_datetime(df["Video publish time"]))
.set_index("date")
.sort_index()
)
clean_df = clean_data(df)
Plot and clip outliers
A line chart of the views is the first look at the series. The chain below lists every later step as a commented line; uncomment a line to apply it.
# Plot the data
(clean_df
.Views
# .clip(upper=150_000)
# .loc["2021":]
# .loc["2021/2":"2021/8"]
# .resample("W")
# .resample("ME")
# .resample("QE")
# .mean()
# .fillna(0)
# .rolling(6)
# .mean()
.plot(kind='line', figsize=(15,3), title="Time Series Analysis")
)

Two outliers flatten everything else. The clip method caps the values at 150,000 views, which makes the pattern of the other videos visible.
Filter by date and resample
With a datetime index, loc filters by date strings: .loc["2021":] keeps everything from 2021 onwards, and .loc["2021/2":"2021/8"] narrows it to February through August.
The resample method groups the rows into periods, here weeks, and mean() returns the mean views per week. Weeks without a video come back empty, which leaves a gap in March and April, so fillna(0) fills them with 0.
# Plot the data
(clean_df
.Views
.clip(upper=150_000)
.loc["2021":]
.loc["2021/2":"2021/8"]
.resample("W")
# .resample("ME")
# .resample("QE")
.mean()
.fillna(0)
# .rolling(6)
# .mean()
.plot(kind='line', figsize=(15,3), title="Time Series Analysis")
)

Monthly or quarterly means work the same way, and a bar chart reads better for a handful of periods. pandas 2.2 and later use the aliases “ME” for month end and “QE” for quarter end; older versions use “M” and “Q”, which pandas 3 rejects.
# Plot the data
(clean_df
.Views
.clip(upper=150_000)
.loc["2021":]
.loc["2021/1":"2021/12"]
# .resample("W")
# .resample("ME")
.resample("QE")
.mean()
.fillna(0)
# .rolling(6)
# .mean()
.plot(kind='bar', figsize=(15,3), title="Time Series Analysis")
)

Moving average
A moving average smooths the weekly values. rolling(6).mean() averages each week with the five weeks before it, so the first five values are empty because they have fewer than six weeks of history.
# Plot the data
(clean_df
.Views
.clip(upper=150_000)
.loc["2021":]
.loc["2021/2":"2021/8"]
.resample("W")
# .resample("ME")
# .resample("QE")
.mean()
.fillna(0)
.rolling(6)
.mean()
.plot(kind='line', figsize=(15,3), title="Time Series Analysis")
)

Moving average on stock prices
The same rolling mean is a classic on stock prices. The yfinance package downloads three months of Microsoft prices, a new column holds the 15-day rolling average of the adjusted close, and the chart shows both lines.
pip install -U yfinance
import yfinance as yf
# get data from yfinance
data = yf.download(
tickers="MSFT", period="3mo", auto_adjust=False, multi_level_index=False
)
data.head()
auto_adjust=False keeps the Adj Close column, which recent yfinance versions leave out by default, and multi_level_index=False gives single-level column names. I cover the download itself in getting stock data into Excel with Python.
# plot adj close + simple moving average 15 days
(data
.assign(SMA15=data["Adj Close"].rolling(window=15).mean())
.filter(items=["Adj Close", "SMA15"])
.plot(figsize=(15, 3), title="SMA - 15 days")
)

For price data, a candlestick chart in Plotly shows more than a line. To see daily values as a calendar instead, try a calendar heatmap.
