Customer segmentation pattern in Data Analysis Python - Time & Space Complexity
We want to understand how the time needed to group customers grows as the number of customers increases.
How does the work change when we have more customers to segment?
Analyze the time complexity of the following code snippet.
import pandas as pd
def segment_customers(df):
segments = {}
for _, row in df.iterrows():
key = (row['age_group'], row['income_level'])
segments.setdefault(key, []).append(row['customer_id'])
return segments
This code groups customers by their age group and income level into segments.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each customer record once.
- How many times: Exactly once per customer, so as many times as there are customers.
As the number of customers grows, the time to process grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 operations |
| 100 | 100 operations |
| 1000 | 1000 operations |
Pattern observation: Doubling customers roughly doubles the work.
Time Complexity: O(n)
This means the time grows directly with the number of customers.
[X] Wrong: "Grouping customers by multiple features means the time grows much faster, like squared."
[OK] Correct: The code only loops once through the data, grouping happens during that single pass, so time grows linearly, not squared.
Understanding how grouping scales helps you explain data processing steps clearly and confidently in real projects.
"What if we nested loops to compare each customer with every other customer? How would the time complexity change?"
Practice
Solution
Step 1: Understand the purpose of segmentation
Customer segmentation means dividing customers into groups with similar traits.Step 2: Identify the correct goal
The goal is to group customers, not delete or randomly increase them.Final Answer:
To group customers based on similar characteristics -> Option AQuick Check:
Segmentation = Grouping customers [OK]
- Thinking segmentation deletes data
- Confusing segmentation with random customer increase
- Assuming segmentation creates one big group
Solution
Step 1: Recall common libraries for clustering
KMeans clustering is part of machine learning, often done with scikit-learn.Step 2: Match library to KMeans
scikit-learn provides KMeans; matplotlib is for plotting, pandas for data frames, numpy for arrays.Final Answer:
scikit-learn -> Option AQuick Check:
KMeans = scikit-learn [OK]
- Choosing matplotlib for clustering
- Confusing pandas with clustering tools
- Selecting numpy instead of scikit-learn
import pandas as pd
from sklearn.cluster import KMeans
data = pd.DataFrame({'Age': [25, 45, 35, 50], 'Income': [50000, 80000, 60000, 90000]})
model = KMeans(n_clusters=2, random_state=0)
model.fit(data)
print(model.labels_)Solution
Step 1: Understand KMeans clustering with 2 clusters
The model groups similar rows into 2 clusters based on Age and Income.Step 2: Predict cluster labels for each row
Rows 0 and 2 are younger with lower income, likely cluster 1; rows 1 and 3 older with higher income, cluster 0.Final Answer:
[1 1 0 0] -> Option BQuick Check:
Similar customers grouped as [1 1 0 0] [OK]
- Assuming clusters are assigned randomly
- Mixing cluster labels order
- Forgetting random_state fixes output
from sklearn.cluster import KMeans
import pandas as pd
data = pd.DataFrame({'Age': [22, 34, 29], 'Income': [40000, 60000, 50000]})
model = KMeans(n_clusters=3)
model.fit(data)
print(model.labels_)Solution
Step 1: Check code syntax and usage
Code imports libraries, creates DataFrame, fits KMeans with 3 clusters, and prints labels.Step 2: Verify if code runs without error
random_state is optional; columns as strings are correct; normalization is recommended but not required.Final Answer:
No error; code runs correctly and prints labels -> Option CQuick Check:
Code runs fine without random_state [OK]
- Thinking random_state is mandatory
- Believing normalization is required to run
- Confusing column names with data types
Solution
Step 1: Prepare data by normalizing numeric columns
Scaling ensures Age, Income, and Spending Score have equal influence on clustering.Step 2: Set number of clusters and fit KMeans
Choose n_clusters=3 as desired segments, then fit model and assign labels.Final Answer:
Normalize numeric columns, choose n_clusters=3, fit KMeans, assign labels to customers -> Option DQuick Check:
Scaling + correct clusters = proper segmentation [OK]
- Skipping normalization causing biased clusters
- Choosing wrong number of clusters
- Using non-numeric data without conversion
Ready to prove it?
Pass the test and this pattern moves unknown
