Complete Pandas Tutorial: Analyzing Data with Python
A full analysis of a real dataset in pandas: load my YouTube channel data, check types, missing values, distributions and correlations, clean it in one chained function, then plot views over time, the top videos per metric and a word cloud of the titles.
Table of contents
Install the dependencies
The analysis uses pandas, matplotlib, seaborn, Plotly, wordcloud and skimpy. Install them from the requirements.txt file in the GitHub repository, or uncomment the cell below to install them into the current Jupyter kernel. The pinned versions are the ones I recorded with.
# import sys
# !{sys.executable} -m pip install matplotlib==3.3.3 -q
# !{sys.executable} -m pip install seaborn==0.11.1 -q
# !{sys.executable} -m pip install plotly==4.14.3 -q
# !{sys.executable} -m pip install wordcloud==1.8.1 -q
# !{sys.executable} -m pip install pandas==1.4.3 -q
# !{sys.executable} -m pip install skimpy==0.0.6 -q
import matplotlib.pyplot as plt
import pandas as pd
import plotly.express as px
import seaborn as sns
from skimpy import clean_columns
from wordcloud import WordCloud
# Display float with 2 decimal values
pd.options.display.float_format = '{:.2f}'.format
Get and inspect the data
The data is a CSV export of my YouTube analytics, hosted on GitHub. pd.read_csv reads it straight from the URL into a dataframe. Five random rows show the columns: video ID, title, publish time, comments, average percentage viewed, likes, views, impressions and click-through rate.
I work through it by hand here. When you only want the overview, you can generate a full EDA report in three lines of code.
raw = pd.read_csv("https://raw.githubusercontent.com/Sven-Bo/datasets/master/YouTube_Data.csv")
# Sample the data
raw.sample(5)
# Get an overview of the data
raw.info()
# Check for missing values abs
raw.isna().sum()
# Check for missing values in %
raw.isna().mean().mul(100)
# Display rows with missing values
raw[raw.isnull().any(axis="columns")]
Missing values
The video publish time column has 4.7% missing values, and it is stored as text. The info method shows both: the data type pandas assigned to each column (publish time is an object and needs converting to a datetime later) and the non-null counts.
isna followed by sum counts the missing values per column. Five missing entries are hard to judge on their own, so mean times 100 turns the count into a percentage.

Distribution
The data is skewed: for comments, likes, views and impressions the mean is far above the median, so a few videos carry most of the numbers. describe shows this at a glance, and I transpose it so the columns read as rows. The average percentage viewed even tops 100% for one video, and nlargest finds which ones.
# Generate descriptive statistics
raw.describe().T
# Inspect highest average percentage viewed
raw.nlargest(5, columns=["Average percentage viewed (%)"])
# Most features (columns) are showing a difference between mean <> median
# This indicates that the data is skewed
hist = raw.hist(bins=15, figsize=(16,10))
count mean std min 25% 50% 75% max
Comments added 107.00 37.24 89.53 0.00 8.50 21.00 33.50 885.00
Average percentage viewed (%) 107.00 33.75 16.57 12.62 23.55 28.91 38.79 102.23
Likes 107.00 417.86 1081.01 0.00 92.50 203.00 352.50 10175.00
Views 107.00 17792.68 50709.27 3.00 2582.00 6382.00 12968.50 442044.00
Impressions 107.00 249785.20 1133091.96 0.00 43961.00 79838.00 132846.50 11550064.00
Impressions click-through rate (%) 106.00 4.46 2.06 0.00 3.06 4.17 5.73 10.86
Correlations
corr computes the Pearson correlation between every pair of numeric columns. Values close to 1 mean a strong positive relationship, values close to -1 a negative one. A background gradient turns the table into a heatmap, and seaborn draws the same as a chart.
The dataset also has text and date columns, so pass numeric_only=True (pandas 1.5 or later). Since pandas 2.0, corr() raises an error without it.
# Check correlation of the features (columns)
(raw
.corr(numeric_only=True)
.style
.background_gradient(cmap='RdBu', vmin=-1, vmax=1)
)
# Plot heatmap
heatmap = sns.heatmap(raw.corr(numeric_only=True), cmap="BuPu", annot=True, fmt=".3f")

Clean the data
All cleaning happens in one function built from chained pandas methods. It drops two columns, removes rows with missing publish times or click-through rates using dropna, cleans the headers into snake_case, keeps videos above a view threshold, converts the publish time to a datetime and adds ratio columns such as likes per day.
Chaining lets you filter, select and rename in one expression. Putting each method on its own line inside parentheses makes it easy to debug, because you can comment out one step at a time. The header cleanup with skimpy is a trick of its own, which I cover in cleaning up column headers in pandas.
# You can chain pandas method like so:
raw.query("Views > 1000").filter(regex="^V", axis="columns").rename(columns={"Video title": "Video_title"})
# You can also break it down into multiple lines
# By doing so, it makes it easier to debug, as you can comment out line by line
(raw
.query("Views > 1000")
.filter(regex="^V", axis="columns")
.rename(columns={"Video title": "Video_title"})
)
# For reference the initial dataframe
raw.head(3)
def clean_df(df, views_threshold=500):
remove_cols = ["Impressions", "Content"]
remove_nan_values = ["Video publish time", "Impressions click-through rate (%)"]
return (df
.drop(labels=remove_cols, axis="columns")
.dropna(subset=remove_nan_values)
.pipe(clean_columns)
.rename(
columns={
"impressions_click_through_rate_%": "impressions_ctr_pct",
"average_percentage_viewed_%": "average_viewed_pct"
}
)
.query("views > @views_threshold")
.assign(video_publish_time=lambda df_: pd.to_datetime(df_.video_publish_time),
days_since_published=lambda df_: (pd.to_datetime("today") - df_.video_publish_time).dt.days.astype(int),
likes_per_day=lambda df_: (df_.likes / df_.days_since_published).round(2),
likes_to_view_ratio_pct=lambda df_: ((df_.likes / df_.views) * 100).round(2),
comments_to_view_ratio_pct=lambda df_: ((df_.comments_added / df_.views) * 100).round(2),
)
)
df = clean_df(raw)
df.head(3)
Views over time
With the publish time as a sorted index, the clean dataframe becomes a time series. The pandas plot method draws a quick line chart. Plotly Express gives an interactive one: hover over a peak and it shows the video title and its numbers for that date.
def plot_timeseries(df, columns):
df = df.set_index("video_publish_time").sort_index()
fig = px.line(
df,
x=df.index,
y=columns,
template="simple_white",
hover_name="video_title",
title=f"Development: {', '.join(columns).title()}",
)
fig.update_layout(hovermode="x unified", margin=dict(l=0, r=0, t=50, b=5))
return fig
fig = plot_timeseries(df=df, columns=["views", "likes", "comments_added"])
fig.show()

To polish charts like this, see these Plotly Express fixes. Resampling by week or month and moving averages go further in time series data manipulation with pandas.
Top videos per metric
One reusable function plots the top videos for any numeric column as a horizontal bar chart, with dotted lines for the mean and the median. List the numeric columns first to see what you can pass in. Ratio columns such as the likes-to-view ratio are useful here, because they are not dominated by the one video with the most views.
def plot_column(df, column, top_values=10, color="#d33682"):
df = df.nlargest(top_values, columns=column).sort_values(by=column)
title = f"<b>{column.replace('_',' ').replace('pct','%').title()} - Top {top_values} videos</b>"
mean = df[column].mean()
median = df[column].median()
fig = px.bar(
df,
x=column,
y="video_title",
orientation="h",
title=title,
color_discrete_sequence=[color] * top_values,
template="plotly_white",
text=column,
)
# add a vertical "mean" line
fig.add_vline(
x=mean,
line_color="gray",
line_width=3,
opacity=1,
line_dash="dot",
annotation_position="top",
annotation=dict(text="<i>mean</i>", font_size=12, font_color="gray"),
)
# add a vertical "mediam" line
fig.add_vline(
x=median,
line_color="salmon",
line_width=3,
opacity=1,
line_dash="dot",
annotation_position="bottom",
annotation=dict(text="<i>median</i>", font_size=12, font_color="salmon"),
)
fig.update_layout(
plot_bgcolor="rgba(0,0,0,0)",
yaxis=(dict(showgrid=False, title=None)),
xaxis=(dict(showgrid=False, title=None, showticklabels=False)),
margin=dict(l=0, r=0, t=50, b=5),
)
return fig
# print all numeric columns
df.select_dtypes('number').columns.to_list()
fig = plot_column(df=df, column="likes", top_values=8)
fig.show()
# Optional: Export the chart to a standalone HTML file
# fig.write_html("chart.html")

Word cloud of the titles
A word cloud of all video titles shows the main topics of the channel at a glance: Excel, Python, Streamlit, pandas and VBA. Setting collocations=False stops the library from counting word pairs as separate entries.
The word cloud options are explained in creating a word cloud in Python.
def generate_wordcloud(df, column, max_font_size=60, collocations=False):
text = df[column].values
return WordCloud(max_font_size=max_font_size, collocations=collocations).generate(str(text))
wordcloud = generate_wordcloud(df, "video_title")
plt.imshow(wordcloud)
plt.axis("off")
plt.show()

