Bird
Raised Fist0
Data Analysis Pythondata~10 mins

Customer segmentation pattern in Data Analysis Python - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Customer segmentation pattern
Load customer data
↓
Select features for segmentation
↓
Apply clustering algorithm
↓
Assign cluster labels to customers
↓
Analyze and visualize segments
↓
Use segments for targeted actions
This flow shows how customer data is loaded, features are selected, clustering groups customers, and segments are analyzed for business use.
Execution Sample
Data Analysis Python
import pandas as pd
from sklearn.cluster import KMeans

# Load data
customers = pd.DataFrame({'Age':[25,45,35,23,52],'Income':[50000,64000,58000,45000,72000]})

# Cluster
kmeans = KMeans(n_clusters=2, random_state=0).fit(customers)
customers['Segment'] = kmeans.labels_
This code loads a small customer dataset, applies KMeans clustering with 2 groups, and assigns segment labels.
Execution Table
StepActionData ShapeCluster CentersSegment Labels
1Load customer data(5, 2)N/AN/A
2Initialize KMeans with 2 clusters(5, 2)N/AN/A
3Fit KMeans to data(5, 2)[[24.0, 47500.0], [44.0, 64666.66666667]]N/A
4Assign cluster labels(5, 3)[[24.0, 47500.0], [44.0, 64666.66666667]][0, 1, 1, 0, 1]
5Final segmented data(5, 3)[[24.0, 47500.0], [44.0, 64666.66666667]][0, 1, 1, 0, 1]
💡 Clustering complete, segments assigned to all customers.
Variable Tracker
VariableStartAfter Step 3After Step 4Final
customersEmpty(5, 2) DataFrame(5, 3) DataFrame(5, 3) DataFrame with Segment
kmeans.cluster_centers_N/A[[24.0, 47500.0], [44.0, 64666.66666667]][[24.0, 47500.0], [44.0, 64666.66666667]][[24.0, 47500.0], [44.0, 64666.66666667]]
kmeans.labels_N/AN/A[0, 1, 1, 0, 1][0, 1, 1, 0, 1]
Key Moments - 3 Insights
Why do the cluster centers have values like [24.0, 47500.0]?
These centers represent the average Age and Income of customers in each cluster, calculated during fitting (see Step 3 in execution_table).
Why are segment labels assigned only after fitting the model?
Labels depend on the clustering result, so they are only available after the model learns clusters from data (see Step 4).
What does the 'Segment' column in the final DataFrame represent?
It shows which cluster each customer belongs to, enabling segmentation for analysis or marketing (see Step 5).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at Step 4, what is the segment label for the customer with Age 35?
A1
B0
C2
DN/A
💡 Hint
Check the Segment Labels column at Step 4; the third label corresponds to the third customer (Age 35).
At which step do we first see the cluster centers calculated?
AStep 2
BStep 4
CStep 3
DStep 5
💡 Hint
Look at the Cluster Centers column; centers appear after fitting the model.
If we change n_clusters to 3, what will change in the execution_table?
ASegment labels will remain the same
BNumber of cluster centers will be 3
CData shape will change
DCluster centers will be empty
💡 Hint
Number of clusters controls how many centers are computed (see Step 3 Cluster Centers).
Concept Snapshot
Customer Segmentation Pattern:
- Load customer data with features (e.g., Age, Income)
- Use clustering (e.g., KMeans) to group customers
- Assign cluster labels as segments
- Analyze segments for targeted marketing
- Key: cluster centers represent group averages
Full Transcript
Customer segmentation groups customers by similar traits. We load data, select features like Age and Income, then apply KMeans clustering. The algorithm finds cluster centers representing average customer profiles. Each customer gets a segment label showing their group. This helps businesses target marketing or services. The execution table shows steps from loading data to assigning segments. Variable tracking shows how data and model outputs change. Key moments clarify cluster centers and label assignment. Quizzes test understanding of labels, cluster centers, and effect of changing cluster count.

Practice

(1/5)
1. What is the main goal of customer segmentation in data science?
easy
A. To group customers based on similar characteristics
B. To delete customer data from the database
C. To increase the number of customers randomly
D. To create a single profile for all customers

Solution

  1. Step 1: Understand the purpose of segmentation

    Customer segmentation means dividing customers into groups with similar traits.
  2. Step 2: Identify the correct goal

    The goal is to group customers, not delete or randomly increase them.
  3. Final Answer:

    To group customers based on similar characteristics -> Option A
  4. Quick Check:

    Segmentation = Grouping customers [OK]
Hint: Segmentation means grouping similar customers [OK]
Common Mistakes:
  • Thinking segmentation deletes data
  • Confusing segmentation with random customer increase
  • Assuming segmentation creates one big group
2. Which Python library is commonly used for KMeans clustering in customer segmentation?
easy
A. scikit-learn
B. matplotlib
C. pandas
D. numpy

Solution

  1. Step 1: Recall common libraries for clustering

    KMeans clustering is part of machine learning, often done with scikit-learn.
  2. Step 2: Match library to KMeans

    scikit-learn provides KMeans; matplotlib is for plotting, pandas for data frames, numpy for arrays.
  3. Final Answer:

    scikit-learn -> Option A
  4. Quick Check:

    KMeans = scikit-learn [OK]
Hint: KMeans is in scikit-learn library [OK]
Common Mistakes:
  • Choosing matplotlib for clustering
  • Confusing pandas with clustering tools
  • Selecting numpy instead of scikit-learn
3. What will be the output of this code snippet?
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_)
medium
A. [1 0 1 0]
B. [1 1 0 0]
C. [0 0 1 1]
D. [0 1 0 1]

Solution

  1. Step 1: Understand KMeans clustering with 2 clusters

    The model groups similar rows into 2 clusters based on Age and Income.
  2. 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.
  3. Final Answer:

    [1 1 0 0] -> Option B
  4. Quick Check:

    Similar customers grouped as [1 1 0 0] [OK]
Hint: Younger & lower income cluster 1, older & higher income cluster 0 [OK]
Common Mistakes:
  • Assuming clusters are assigned randomly
  • Mixing cluster labels order
  • Forgetting random_state fixes output
4. Identify the error in this customer segmentation code:
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_)
medium
A. KMeans requires data to be normalized before fitting
B. DataFrame columns should be strings, not numbers
C. No error; code runs correctly and prints labels
D. Missing random_state parameter in KMeans

Solution

  1. Step 1: Check code syntax and usage

    Code imports libraries, creates DataFrame, fits KMeans with 3 clusters, and prints labels.
  2. Step 2: Verify if code runs without error

    random_state is optional; columns as strings are correct; normalization is recommended but not required.
  3. Final Answer:

    No error; code runs correctly and prints labels -> Option C
  4. Quick Check:

    Code runs fine without random_state [OK]
Hint: random_state optional; code runs if syntax correct [OK]
Common Mistakes:
  • Thinking random_state is mandatory
  • Believing normalization is required to run
  • Confusing column names with data types
5. You have customer data with Age, Income, and Spending Score. You want to create 3 segments using KMeans. Which steps should you follow to prepare and segment the data correctly?
hard
A. Remove Age column, set n_clusters=1, fit KMeans, ignore labels
B. Convert numeric data to strings, set n_clusters=3, fit KMeans, assign labels
C. Use raw data without scaling, set n_clusters=5, fit KMeans, assign labels
D. Normalize numeric columns, choose n_clusters=3, fit KMeans, assign labels to customers

Solution

  1. Step 1: Prepare data by normalizing numeric columns

    Scaling ensures Age, Income, and Spending Score have equal influence on clustering.
  2. Step 2: Set number of clusters and fit KMeans

    Choose n_clusters=3 as desired segments, then fit model and assign labels.
  3. Final Answer:

    Normalize numeric columns, choose n_clusters=3, fit KMeans, assign labels to customers -> Option D
  4. Quick Check:

    Scaling + correct clusters = proper segmentation [OK]
Hint: Always scale numeric data before KMeans clustering [OK]
Common Mistakes:
  • Skipping normalization causing biased clusters
  • Choosing wrong number of clusters
  • Using non-numeric data without conversion
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard