Mathew K Analytics

Lesson 25 · Social Media Content Analytics

Interpreting Content Trends and Patterns

In this lesson, we will learn how to uncover and interpret trends in social media and content analytics data. Understanding these trends helps creators and…

⬇ Download notebookOpen in Colab ↗

📓 Full notebook

Download .ipynb

Interpreting Content Trends and Patterns#

  • In this lesson, we will learn how to uncover and interpret trends in social media and content analytics data.
  • Understanding these trends helps creators and brands optimize their strategies for growth and engagement.
  • We will use public datasets to identify patterns in audience behavior, measure content performance, and recommend next steps.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')

What are Social Media Analytics Datasets?#

  • Social media datasets include posts, videos, and engagement activity.
  • Each row usually represents a post, video, or day of engagement.
  • Metrics include views, likes, comments, watch time, CTR, and shares.
  • Beginners often confuse total and average metrics, or misuse ratios.
  • Always double-check what each metric means before analyzing trends.
# Example: Load the Social Media Content dataset
np.random.seed(42)
n_posts = 500
views = np.random.randint(100, 100000, n_posts)
df = pd.DataFrame({
    'post_id': range(1, n_posts+1),
    'platform': np.random.choice(['YouTube','Instagram','TikTok'], n_posts),
    'date': pd.date_range('2023-01-01', periods=n_posts, freq='6h'),
    'views': views,
    'likes': (views * np.random.uniform(0.02, 0.15, n_posts)).astype(int),
    'comments': (views * np.random.uniform(0.001, 0.05, n_posts)).astype(int),
    'shares': (views * np.random.uniform(0.001, 0.03, n_posts)).astype(int)
})
print(df.shape)
df.head(3)
(500, 7)
post_id platform date views likes comments shares
0 1 Instagram 2023-01-01 00:00:00 15895 2356 116 253
1 2 Instagram 2023-01-01 06:00:00 960 94 16 26
2 3 Instagram 2023-01-01 12:00:00 76920 3910 2879 1185

Beginner Example 1: Calculate Overall Engagement Rate#

  • Engagement rate tells us how active the audience is per post.
  • A high engagement rate shows that content is connecting with fans.
  • Calculate engagement rate as (likes + comments + shares) / views.
# Calculate engagement rate for each post
df['engagement_rate'] = (df['likes'] + df['comments'] + df['shares']) / df['views']
print('Mean engagement rate: {:.2%}'.format(df['engagement_rate'].mean()))
df[['platform','engagement_rate']].head()
Mean engagement rate: 12.61%
platform engagement_rate
0 Instagram 0.171438
1 Instagram 0.141667
2 Instagram 0.103666
3 YouTube 0.071873
4 Instagram 0.106363

Beginner Example 2: Compare Platforms by Average Engagement#

  • Platforms can have very different audience habits.
  • Find out which platform gets the highest engagement on average.
  • This helps creators focus on where their audience is most active.
# Group by platform to compare engagement rates
platform_avg_engagement = df.groupby('platform')['engagement_rate'].mean().sort_values(ascending=False)
print(platform_avg_engagement)
platform_avg_engagement.plot(kind='bar', color=['#FF0000','#C13584','#69C9D0'])
plt.ylabel('Average Engagement Rate')
plt.title('Average Engagement Rate by Platform')
plt.show()
platform
Instagram    0.130443
TikTok       0.126907
YouTube      0.121630
Name: engagement_rate, dtype: float64
No description has been provided for this image

Beginner Example 3: See Engagement Trends Over Time#

  • Looking at trends helps us spot seasonality or growth.
  • Plot daily average engagement rate to see if it changes with time.
  • Upward or downward patterns can signal content improvement or declining interest.
# Calculate daily average engagement rate
df['date_only'] = df['date'].dt.date
daily_trend = df.groupby('date_only')['engagement_rate'].mean()
plt.figure(figsize=(10,4))
daily_trend.plot()
plt.ylabel('Avg Engagement Rate')
plt.xlabel('Date')
plt.title('Daily Engagement Rate Trend')
plt.tight_layout()
plt.show()
No description has been provided for this image

Intermediate Example 1: Find Top-Performing Posts#

  • Spotting top content helps you learn what works.
  • Find the 10 posts with the highest engagement rates.
  • Analyze features of your best-performing posts.
# Get top 10 posts by engagement rate
top_posts = df.sort_values('engagement_rate', ascending=False).head(10)
print(top_posts[['platform','date','views','engagement_rate']])
      platform                date  views  engagement_rate
351  Instagram 2023-03-29 18:00:00  74643         0.217810
10   Instagram 2023-01-03 12:00:00  16123         0.212057
383     TikTok 2023-04-06 18:00:00  36731         0.209251
423     TikTok 2023-04-16 18:00:00  53021         0.208823
87      TikTok 2023-01-22 18:00:00  82898         0.206989
310     TikTok 2023-03-19 12:00:00  77605         0.204072
429     TikTok 2023-04-18 06:00:00  56761         0.200948
56   Instagram 2023-01-15 00:00:00  36020         0.200944
182  Instagram 2023-02-15 12:00:00  61473         0.200316
335     TikTok 2023-03-25 18:00:00  47433         0.199334

Intermediate Example 2: Platform Performance Over Time#

  • Compare engagement rate trends across platforms.
  • Visualize if one platform is growing faster or has steadier engagement.
# Plot engagement trends by platform
platform_trend = df.groupby(['date_only','platform'])['engagement_rate'].mean().unstack()
platform_trend.plot(figsize=(12,6))
plt.ylabel('Avg Engagement Rate')
plt.title('Engagement Rate Trend by Platform')
plt.legend(title='Platform')
plt.tight_layout()
plt.show()
No description has been provided for this image

Intermediate Example 3: Find Outliers and Anomalies#

  • Outliers can signal viral content or errors.
  • Use a boxplot to spot posts with extremely high or low engagement rates.
# Boxplot for engagement rate across platforms
plt.figure(figsize=(8,5))
sns.boxplot(x='platform', y='engagement_rate', data=df, palette='pastel')
plt.ylabel('Engagement Rate')
plt.title('Engagement Rate Distribution per Platform')
plt.show()
No description has been provided for this image

Advanced Example 1: Audience Activity Time Patterns#

  • Find what times of day get most engagement.
  • This can inform when to post for maximum reach.
# Extract hour from date and analyze average engagement rate by posting hour
df['post_hour'] = df['date'].dt.hour
hourly_engagement = df.groupby('post_hour')['engagement_rate'].mean()
plt.figure(figsize=(8,4))
hourly_engagement.plot(kind='bar', color='#36a2eb')
plt.xlabel('Hour of Day')
plt.ylabel('Mean Engagement Rate')
plt.title('Average Engagement Rate by Posting Hour')
plt.tight_layout()
plt.show()
No description has been provided for this image

Advanced Example 2: Viral Content Detection#

  • Viral posts stand out for unusually high engagement rates.
  • Set a threshold at top 1% engagement rate to flag likely viral posts.
# Detect viral posts: posts above the 99th percentile engagement rate
threshold = df['engagement_rate'].quantile(0.99)
viral_posts = df[df['engagement_rate'] >= threshold]
print('Number of viral posts:', len(viral_posts))
viral_posts[['platform','date','views','engagement_rate']]
Number of viral posts: 5
platform date views engagement_rate
10 Instagram 2023-01-03 12:00:00 16123 0.212057
87 TikTok 2023-01-22 18:00:00 82898 0.206989
351 Instagram 2023-03-29 18:00:00 74643 0.217810
383 TikTok 2023-04-06 18:00:00 36731 0.209251
423 TikTok 2023-04-16 18:00:00 53021 0.208823

Error Handling: Dealing with Missing Engagement Data#

  • Sometimes engagement values are missing or zero.
  • Fill missing values with zeros so calculations are not biased.
# Introduce missing values artificially for demonstration
df_missing = df.copy()
df_missing.loc[np.random.choice(df_missing.index, size=10), 'likes'] = np.nan
print('Missing likes before:', df_missing["likes"].isna().sum())
df_missing['likes'] = df_missing['likes'].fillna(0)
print('Missing likes after:', df_missing["likes"].isna().sum())
Missing likes before: 10
Missing likes after: 0

Error Handling: Incorrect Aggregation Example#

  • Summing engagement rates directly over groups is incorrect.
  • Always take the mean of engagement rates, not sum, when grouping data.
# Incorrect: Summing engagement rates
agg_sum = df.groupby('platform')['engagement_rate'].sum()
print('Summing engagement rates (incorrect):\n', agg_sum)
# Correct: Taking mean engagement rate
agg_mean = df.groupby('platform')['engagement_rate'].mean()
print('\nMean engagement rates (correct):\n', agg_mean)
Summing engagement rates (incorrect):
 platform
Instagram    21.131792
TikTok       19.416840
YouTube      22.501569
Name: engagement_rate, dtype: float64

Mean engagement rates (correct):
 platform
Instagram    0.130443
TikTok       0.126907
YouTube      0.121630
Name: engagement_rate, dtype: float64

Best Practices: Interpreting Social Media Patterns#

  • Benchmark against previous performance, not just latest data.
  • Segment your audience to discover hidden trends.
  • Check for growth over time, not just high single posts.
  • Use clear, consistent metric definitions so results are comparable.
  • Always place patterns in the right context.

Analytics Pattern: Benchmarking Content Against Previous Month#

  • See if your average engagement rate this month is up or down compared to last month.
  • This pattern helps you measure progress.
# Monthly engagement rate benchmarking
df['month'] = df['date'].dt.to_period('M')
monthly_mean = df.groupby('month')['engagement_rate'].mean()
print(monthly_mean.tail(2))
monthly_mean.plot(marker='o', linestyle='-', figsize=(10,4))
plt.title('Monthly Engagement Rate Trend')
plt.ylabel('Average Engagement Rate')
plt.xlabel('Month')
plt.tight_layout()
plt.show()
month
2023-04    0.129180
2023-05    0.143788
Freq: M, Name: engagement_rate, dtype: float64
No description has been provided for this image

Analytics Pattern: Consistent Metric Definitions#

  • Always define engagement rates the same way across reports.
  • Use functions to avoid typos or changes in formulas.
# Define a function for engagement rate
def calc_engagement_rate(df):
    return (df['likes'] + df['comments'] + df['shares']) / df['views']
df['engagement_rate_2'] = calc_engagement_rate(df)
print('Results equal:', np.allclose(df['engagement_rate'], df['engagement_rate_2']))
Results equal: True

End-to-End Example: Make a Content Strategy Recommendation#

  • Find your 5 best posts over the past 30 days.
  • Suggest what content or timing should be repeated.
# Filter posts from last 30 days and sort by engagement rate
latest_date = df['date'].max().date()
window_start = latest_date - pd.Timedelta(days=30)
recent = df[df['date'].dt.date >= window_start]
top_recent = recent.sort_values('engagement_rate', ascending=False).head(5)
print(top_recent[['platform','date','views','engagement_rate']])
      platform                date  views  engagement_rate
383     TikTok 2023-04-06 18:00:00  36731         0.209251
423     TikTok 2023-04-16 18:00:00  53021         0.208823
429     TikTok 2023-04-18 06:00:00  56761         0.200948
484  Instagram 2023-05-02 00:00:00   9762         0.196988
392     TikTok 2023-04-09 00:00:00  99813         0.196588
plt.figure(figsize=(8, 4))
plt.bar(top_recent['date'].dt.strftime('%Y-%m-%d'), top_recent['engagement_rate'], color='#2ecc71')
plt.xticks(rotation=45)
plt.ylabel('Engagement Rate')
plt.title('Top 5 Recent Posts: Engagement Rate')
plt.tight_layout()
plt.show()
No description has been provided for this image

YouTube Call to Action#

  • Like this analysis? Subscribe to learn more about content trends!
  • Let us know in the comments what other social analytics topics you are curious about!

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.