0
0
Data Analysis Pythondata~5 mins

Customer segmentation pattern in Data Analysis Python

Choose your learning style9 modes available
Introduction

Customer segmentation helps group customers by similar traits. This makes it easier to understand and serve them better.

When you want to send personalized marketing messages to different groups.
When you want to find which customers are most valuable.
When you want to improve product recommendations based on customer groups.
When you want to analyze customer behavior patterns.
When you want to design targeted promotions for specific customer groups.
Syntax
Data Analysis Python
import pandas as pd
from sklearn.cluster import KMeans

# Load data
# Select features for clustering
# Create KMeans model
# Fit model to data
# Assign cluster labels to data

Use numeric features for clustering.

KMeans is a common method for segmentation.

Examples
This example groups customers into 2 segments based on Age and Spending Score.
Data Analysis Python
import pandas as pd
from sklearn.cluster import KMeans

# Example data
data = pd.DataFrame({
    'Age': [25, 45, 35, 50],
    'SpendingScore': [60, 40, 80, 30]
})

# Create model
kmeans = KMeans(n_clusters=2, random_state=42)

# Fit and predict
clusters = kmeans.fit_predict(data)

# Add cluster labels
data['Segment'] = clusters
print(data)
This example uses Annual Income and Spending Score to create 3 customer segments.
Data Analysis Python
import pandas as pd
from sklearn.cluster import KMeans

# Load data
customers = pd.read_csv('customers.csv')

# Select features
features = customers[['AnnualIncome', 'SpendingScore']]

# Create and fit model
model = KMeans(n_clusters=3, random_state=0)
customers['Segment'] = model.fit_predict(features)

print(customers.head())
Sample Program

This program groups 5 customers into 2 segments using Age, Annual Income, and Spending Score.

Data Analysis Python
import pandas as pd
from sklearn.cluster import KMeans

# Sample customer data
customer_data = pd.DataFrame({
    'CustomerID': [1, 2, 3, 4, 5],
    'Age': [22, 35, 58, 45, 33],
    'AnnualIncome': [15000, 40000, 60000, 52000, 35000],
    'SpendingScore': [39, 81, 6, 77, 40]
})

# Select features for segmentation
features = customer_data[['Age', 'AnnualIncome', 'SpendingScore']]

# Create KMeans model with 2 clusters
kmeans = KMeans(n_clusters=2, random_state=1)

# Fit model and predict clusters
customer_data['Segment'] = kmeans.fit_predict(features)

# Show the data with segments
print(customer_data)
OutputSuccess
Important Notes

Choosing the right number of clusters is important for meaningful segments.

Features should be scaled if they have very different ranges.

Interpret segments by looking at feature averages per group.

Summary

Customer segmentation groups customers by similar traits.

KMeans is a simple way to create segments using numeric data.

Segments help target marketing and improve customer understanding.