Lesson 25 · Market Research Analytics in Python
Interpreting Patterns and Market Trends in Python Market Research Analytics
In this lesson, we will discover how to analyze real-world consumer and market data to identify important patterns and trends. Understanding these patterns…
- CourseMarket Research Analytics in Python
- Lesson25 of 56
- Video23 min
- FormatJupyter notebook · 18 code cells
What you'll learn
- Core Market Research Concepts
- Beginner Example 1: Preview a Customer Satisfaction Survey
- Beginner Example 2: View a Marketing Campaign Dataset
- Beginner Example 3: Get the Range of Customer Ages in a Campaign
- Intermediate Example 1: Calculate Monthly Trend in Online Retail Purchases
- Intermediate Example 2: Visualize Churn Rate Across Contract Types
- Intermediate Example 3: Explore NPS Score Distribution
- Advanced Example 1: Build Customer Cohort Retention Table
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbInterpreting Patterns and Market Trends in Customer Analytics#
- In this lesson, we will discover how to analyze real-world consumer and market data to identify important patterns and trends.
- Understanding these patterns helps businesses improve products, target marketing, and retain customers.
- You will learn how to explore, summarize, and visualize key market research datasets to produce actionable insights.
- By the end, you will interpret real customer responses to support or challenge business decisions.
import pandas as pd
import numpy as np
import openml
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
Core Market Research Concepts#
- We use customer survey data, campaign response data, and retail transaction data.
- Datasets contain customer demographics, satisfaction scores, and purchasing behavior.
- Each row represents an individual response or transaction.
- Mistakes can happen by ignoring missing values, misreading scales, or not grouping data correctly.
- Pay close attention when interpreting trends: context and definitions matter.
Beginner Example 1: Preview a Customer Satisfaction Survey#
- Load a real customer satisfaction dataset from OpenML.
- Preview the first three records to understand structure and values.
dataset = openml.datasets.get_dataset(42178)
csat_df, _, _, _ = dataset.get_data(dataset_format='dataframe')
print(csat_df.shape)
print(csat_df.head(3))
Beginner Example 2: View a Marketing Campaign Dataset#
- Load the OpenML bank marketing dataset.
- Explore three example rows to see typical campaign features.
campaign_dataset = openml.datasets.get_dataset(1461)
campaign_df, _, _, _ = campaign_dataset.get_data(dataset_format='dataframe')
campaign_df.columns = ['age','job','marital','education','default','balance','housing','loan','contact','day','month','duration','campaign','pdays','previous','poutcome','response']
print(campaign_df.shape)
print(campaign_df.head(3))
Beginner Example 3: Get the Range of Customer Ages in a Campaign#
- Identify the youngest and oldest customer in the marketing campaign dataset.
print('Youngest customer age:', campaign_df['age'].min())
print('Oldest customer age:', campaign_df['age'].max())
Intermediate Example 1: Calculate Monthly Trend in Online Retail Purchases#
- Load the online retail dataset and view transaction counts by month.
- This helps uncover seasonality and customer purchase surges.
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/00502/online_retail_II.xlsx'
retail_df = pd.read_excel(url, sheet_name='Year 2010-2011')
retail_df['InvoiceDate'] = pd.to_datetime(retail_df['InvoiceDate'])
monthly_counts = retail_df.groupby(retail_df['InvoiceDate'].dt.to_period('M')).size()
print(monthly_counts.head())
Intermediate Example 2: Visualize Churn Rate Across Contract Types#
- Determine whether contract duration relates to churn in the satisfaction dataset.
- Visualize using a bar plot.
contract_churn = csat_df.groupby('Contract')['Churn'].value_counts(normalize=True).unstack()
contract_churn.plot(kind='bar', stacked=True)
plt.title('Churn Rate by Contract Type')
plt.ylabel('Proportion of Customers')
plt.xlabel('Contract Type')
plt.legend(title='Churn')
plt.tight_layout()
plt.show()
Intermediate Example 3: Explore NPS Score Distribution#
- Generate a synthetic Net Promoter Score dataset and plot its distribution.
- NPS histograms help companies gauge customer loyalty patterns.
np.random.seed(42)
nps_df = pd.DataFrame({
'CustomerID': range(1, 501),
'Age': np.random.randint(18, 70, 500),
'Region': np.random.choice(['North', 'South', 'East', 'West'], 500),
'NPS_Score': np.random.randint(0, 11, 500)
})
sns.histplot(nps_df['NPS_Score'], bins=11, color='skyblue', edgecolor='k')
plt.title('NPS Score Distribution')
plt.xlabel('NPS Score')
plt.ylabel('Number of Customers')
plt.show()
Advanced Example 1: Build Customer Cohort Retention Table#
- Simulate monthly customer signups and activity.
- Visualize retention patterns over two years for trend analysis.
np.random.seed(0)
dates = pd.date_range('2021-01-01', periods=24, freq='M')
cohort_df = pd.DataFrame({
'CustomerID': np.random.randint(1000, 2000, len(dates)),
'Signup_Month': dates,
'Active_Users': np.random.randint(50, 300, len(dates))
})
plt.plot(cohort_df['Signup_Month'], cohort_df['Active_Users'], marker='o')
plt.title('Monthly Active Users in Each Customer Cohort')
plt.xlabel('Signup Month')
plt.ylabel('Active Users')
plt.grid(True)
plt.tight_layout()
plt.show()
Advanced Example 2: Analyze Open-Ended Customer Feedback for Keywords#
- Use keyword frequency to spot growing customer themes in text feedback.
- Quick keyword counts can alert businesses to market shifts.
feedback_df = pd.DataFrame({
'CustomerID': [1, 2, 3, 4, 5],
'Feedback': [
'Great service and friendly staff',
'Delivery was slow and packaging was poor',
'Excellent quality, will buy again',
'Customer support needs improvement',
'Good value for money'
]
})
all_text = ' '.join(feedback_df['Feedback']).lower()
from collections import Counter
words = [word.strip('.,') for word in all_text.split()]
freq = Counter(words)
print('Most common words:', freq.most_common(5))
Error Handling Example 1: Detect and Count Missing Values#
- Market research analysts must always check for missing survey responses.
- How many blanks do you have in the satisfaction dataset?
missing = csat_df.isnull().sum()
print('Missing values by column:')
print(missing[missing > 0])
Error Handling Example 2: Avoid Incorrect Aggregation#
- Beginners often aggregate using the wrong group or logic.
- Here, we try grouping NPS scores by age incorrectly.
# Incorrect: using mean on ID field
print('Average customer ID by age group (nonsense!):')
print(nps_df.groupby(pd.cut(nps_df['Age'], bins=[17,30,50,69]))['CustomerID'].mean())
Error Handling Example 3: Misinterpreting Response Scales#
- Let us convert an NPS score to categories and examine if anyone mislabels the 7 or 8 responses.
- Correct segmentation is critical for interpreting loyalty.
def label_nps(score):
if score >= 9:
return 'Promoter'
elif score >= 7:
return 'Passive'
else:
return 'Detractor'
nps_df['Category'] = nps_df['NPS_Score'].apply(label_nps)
print(nps_df['Category'].value_counts())
Best Practices: Segment Customers by Region and NPS#
- Market segmentation helps target strategies and reporting.
- Analyze mean NPS by region in the synthetic survey dataset.
mean_nps_region = nps_df.groupby('Region')['NPS_Score'].mean()
print('Mean NPS by region:')
print(mean_nps_region)
Best Practices: Cross-Tabulate Contract Type and Churn#
- Cross-tabs reveal underlying relationships between categorical variables.
- Here, we examine if contract type is linked to churn in the survey data.
ct = pd.crosstab(csat_df['Contract'], csat_df['Churn'], normalize='index')
print('Churn distribution by contract type:')
print(ct)
Best Practices: Construct Market Indices and Scores#
- Create a simple satisfaction index by averaging several rating columns.
- Composite indices allow clearer trend analysis and benchmarking over time.
# Use 'MonthlyCharges' and 'tenure' as a basic combined 'value index'
csat_df['Value_Index'] = csat_df['MonthlyCharges'] / csat_df['tenure'].replace(0, np.nan)
print('Sample Value_Index for first five customers:')
print(csat_df[['MonthlyCharges','tenure','Value_Index']].head())
Best Practices: Market Trend Analysis with Rolling Means#
- Use a rolling mean to smooth out volatility in monthly transaction counts.
- Simple smoothing can make business cycles easier to explain.
smoothed = monthly_counts.rolling(window=3, min_periods=1).mean()
plt.plot(monthly_counts.index.to_timestamp(), monthly_counts.values, label='Monthly Counts', linestyle='--')
plt.plot(smoothed.index.to_timestamp(), smoothed.values, label='3-Month Rolling Mean', color='red')
plt.title('Monthly Transactions with Trendline')
plt.xlabel('Month')
plt.ylabel('Transactions')
plt.legend()
plt.tight_layout()
plt.show()
Tiny End-to-End Problem: From Raw NPS Data to Market Insight#
- Analyze NPS categories to compute the overall NPS score and present a business summary.
- Recommend if the company should prioritize loyalty improvement.
# Calculate company-level NPS score as (% promoters - % detractors) * 100
promoters = (nps_df['Category'] == 'Promoter').sum()
passives = (nps_df['Category'] == 'Passive').sum()
detractors = (nps_df['Category'] == 'Detractor').sum()
n_customers = len(nps_df)
nps_score = ((promoters - detractors) / n_customers) * 100
print(f'Company NPS Score: {nps_score:.1f}')
if nps_score < 0:
print('Warning: More detractors than promoters. Immediate business action needed!')
elif nps_score < 40:
print('NPS is moderate. Consider initiatives to turn passives into promoters.')
else:
print('Excellent NPS! Maintain programs to keep promoters engaged.')
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



