top of page

How to segment customers with k-means in ChatGPT and check the clusters

8 minutes ago
8 min read
Cover with the title How to segment customers with k-means in ChatGPT and check the clusters over a teal city skyline, Data Studios original cover

ChatGPT can run a k-means customer segmentation on an uploaded CSV because its data analysis feature writes and executes Python code in a stateful Jupyter notebook environment, as OpenAI's Help Center describes it. The clusters it returns depend on choices that the chat answer often glosses over: which columns go into the model, whether they are scaled, how many clusters are requested and how the starting points are seeded. Two runs that differ on any of these can put the same customer in a different segment.


The practical way to use ChatGPT for this task is to let it write and run the clustering, then check the result against a small, known answer before trusting it on the full customer file. The worked example below uses 12 illustrative customers described by recency, order count and spend, gives the prompts, and shows the correct three-segment result computed in Python with pandas and scikit-learn, including the case where skipping feature scaling moves a high-value lapsed customer into the wrong segment.


The task covers the classic RFM-style segmentation that marketing, CRM and BI teams build before a retention campaign or a pricing review: group customers by behavior, describe each group in business terms, and hand a customer-to-segment mapping to the people who will act on it.


··········


CHATGPT DATA ANALYSIS REQUIREMENTS FOR CLUSTERING A CSV.


OpenAI documents the file side of the workflow in two Help Center articles, checked on November 25, 2026. Spreadsheets in XLSX, XLS, CSV, TSV and OpenDocument (.ods) formats can be uploaded, and CSV files and spreadsheets have a size limit of approximately 50 MB, depending on the size of each row. The 2 million token cap that applies to text and document files does not apply to spreadsheets. Uploads are available on Free and paid plans, subject to plan-specific limits and account settings.


The data analysis article states that the Python environment cannot make external web requests or API calls, so every column used for segmentation has to be in the uploaded file or come from a connected source such as Google Drive, OneDrive or SharePoint when connectors are available for the account. OpenAI does not publish a list of installed Python libraries and its documentation does not mention clustering or machine learning by name. The documented capability is broader: running Python-based calculations, transformations and statistical analysis. Asking ChatGPT to state which library and which parameters it used is therefore part of the procedure.


........


Item

What OpenAI documents

Execution

Python in a stateful Jupyter notebook environment

Internet from Python

No external web requests or API calls

Spreadsheet formats

XLSX, XLS, CSV, TSV, ODS

CSV and spreadsheet size

About 50 MB, depending on row size

Upload rate

Up to 80 files every 3 hours

Free plan uploads

3 file uploads per day

Interactive charts

Bar, line, pie and scatter

Library list

Not published


........


OpenAI adds that it may lower upload limits during peak hours and that ChatGPT does not show how much of the rolling upload quota remains. A customer table larger than the 50 MB limit needs to be aggregated to one row per customer before upload, which usually shrinks it dramatically; the approach for files that stay too large is covered in how to analyze a CSV over ChatGPT's 50MB limit.


··········


PREPARING CUSTOMER DATA FOR K-MEANS IN CHATGPT.


K-means works on numeric features measured per customer, so the upload should already have one row per customer and one column per feature. OpenAI's data analysis guidance points the same way for any spreadsheet: descriptive column headers in the first row, one row per record, and no multiple unrelated tables or empty rows splitting the data. Order-level exports should be rolled up first, and duplicate customer IDs removed; cleaning and deduplicating a CSV with ChatGPT describes the row-count checks for that step.


The illustrative dataset below has three features: days since last order, number of orders in the last 12 months and spend in USD over the same period. Customer C09 is deliberately unusual, with a single large order 150 days ago.


........


customer_id

recency_days

orders_12m

spend_usd

C01

5

14

2350

C02

12

11

1980

C03

8

16

2710

C04

3

12

2120

C05

45

5

640

C06

60

4

520

C07

38

6

780

C08

52

3

410

C09

150

1

1850

C10

210

2

180

C11

180

1

120

C12

240

1

60


........


The data is illustrative and exists only to give a result that can be checked by hand and in code. Extreme values deserve a look before clustering because a single very large customer can pull a centroid toward it; detecting outliers with ChatGPT using IQR and z-score checks is a useful pass to run first on real files.


··········


PROMPTING CHATGPT TO RUN THE K-MEANS SEGMENTATION.


A good first prompt fixes every choice that changes the outcome, so that the answer can be reproduced and compared with the expected result.


I uploaded customers.csv with one row per customer.
Use recency_days, orders_12m and spend_usd as features.
1. Standardize the three features (z-scores) before clustering.
2. Run k-means for k = 2 to 5 with n_init=10 and random_state=42,
   and report inertia and silhouette score for each k.
3. Fit the final model with k = 3 and add a column named segment.
4. Show the mean of each feature per segment and the customer IDs in each segment.
5. Show the full Python code you ran and name the library and version used.

A second prompt turns the clusters into something a campaign team can use, without letting the model rename the facts.


Using only the segment means you computed, give each segment a short
descriptive name and one sentence explaining it. Do not change any number.
Then export customer_id and segment to segments.csv.

Keeping the naming step separate from the computation makes it easier to spot when a label does not fit the numbers, for example a segment called "loyal" whose average order count is low.


··········


THE CORRECT K-MEANS RESULT FOR THE EXAMPLE.


The code below reproduces the expected answer. It was executed with pandas 3.0.5 and scikit-learn 1.9.1 on the illustrative data; StandardScaler converts each feature to z-scores, and KMeans uses ten initializations with a fixed seed.


import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score

df = pd.DataFrame({
    "customer_id": [f"C{i:02d}" for i in range(1, 13)],
    "recency_days": [5, 12, 8, 3, 45, 60, 38, 52, 150, 210, 180, 240],
    "orders_12m": [14, 11, 16, 12, 5, 4, 6, 3, 1, 2, 1, 1],
    "spend_usd": [2350, 1980, 2710, 2120, 640, 520, 780, 410, 1850, 180, 120, 60],
})
features = ["recency_days", "orders_12m", "spend_usd"]
X = StandardScaler().fit_transform(df[features])

for k in range(2, 6):
    km = KMeans(n_clusters=k, n_init=10, random_state=42).fit(X)
    print(k, round(km.inertia_, 2), round(silhouette_score(X, km.labels_), 3))

df["segment"] = KMeans(n_clusters=3, n_init=10, random_state=42).fit_predict(X)
print(df.groupby("segment")[features].mean().round(1))
print(df.groupby("segment")["customer_id"].apply(list))

The scores for each k on the standardized features are these.


........


k

Inertia

Silhouette

2

11.42

0.587

3

4.45

0.631

4

1.49

0.685

5

0.78

0.603


........


The silhouette score peaks at k = 4, and the fourth cluster contains a single customer, C09. A segment of one customer is an outlier rather than a group anyone can target, so the example keeps k = 3 and treats C09 as a case for manual review. That choice is a business judgment, and the prompt should ask ChatGPT to show the members of each cluster so the reviewer can make it.


With k = 3, the segments and their feature means are as follows. The numeric label of each segment can differ between runs and libraries; the membership is what has to match. Across 50 different random seeds the three-cluster partition was identical in every run.


........


Segment

Customers

Avg recency (days)

Avg orders

Avg spend (USD)

Total spend (USD)

Active high value

C01, C02, C03, C04

7.0

13.25

2290.0

9160

Occasional

C05, C06, C07, C08

48.75

4.5

587.5

2350

Lapsed

C09, C10, C11, C12

195.0

1.25

552.5

2210


........


Total spend across the 12 customers is 13,720 USD. The active segment accounts for 66.8% of it, the occasional segment 17.1% and the lapsed segment 16.1%. Within the lapsed segment, C09 alone contributes 1,850 USD, or 83.7% of that segment's spend, which is why its average spend is close to the occasional segment's despite much lower activity.


··········


WHAT CHATGPT TENDS TO GET WRONG IN K-MEANS SEGMENTATION.


The most consequential error is clustering unscaled features. Spend in this example ranges into thousands of dollars while order counts stay below 20, so distances are dominated by spend. Running the same k = 3 model on the raw columns puts C09 in the same cluster as C01 to C04, because its 1,850 USD is close to their spend, even though it has ordered once in a year and not in 150 days. On standardized data C09 lands with the lapsed customers. If ChatGPT's membership list shows C09 among the active customers, the features were almost certainly not scaled.


Other checks are mechanical and quick. The segment counts must add up to the number of unique customers in the file. The feature means per segment should be recomputed from the exported segments.csv with a simple group-by, outside the chat, because a summary paragraph can drift from the table it describes. The code ChatGPT shows should match the parameters requested, including n_init and random_state; OpenAI's own guidance asks users to review generated code, outputs and assumptions before relying on a result, and warns that ChatGPT may choose a method that does not match the intent on the first try.


Segment names are the part that most needs a human. A label such as "at risk" or "VIP" drives who receives a discount or a call, and the model only sees three averages. The same discipline applies to related analyses such as building a cohort retention table with ChatGPT, where the computed table is checked first and the interpretation comes second.


··········


CUSTOMER DATA PRIVACY WHEN CLUSTERING IN CHATGPT.


Segmentation does not need names, emails or addresses, so the safest upload contains a pseudonymous customer ID and the numeric features only, with the mapping back to real identities kept in the company's own systems. OpenAI states that it does not use content submitted by customers to business offerings, such as the API and ChatGPT Enterprise, to improve model performance; for consumer plans it refers users to its data controls settings. Retention of uploaded files depends on where the file is stored and on any workspace retention policy, and in Enterprise, Edu and Healthcare workspaces files saved to the Library follow the workspace retention policy.


··········


K-MEANS SEGMENTATION IN CHATGPT: WHAT TO CONFIRM BEFORE USING THE SEGMENTS.


OpenAI documents the Python execution environment, the file formats and the roughly 50 MB spreadsheet limit, and it documents that the environment has no internet access. It does not document which libraries are installed or name clustering as a feature, so the library and version should come from ChatGPT's own code output on each run. Upload allowances vary by plan and can be lowered at peak times.


The result itself depends on four inputs the analyst controls: the feature list, scaling, the number of clusters and the seed. With standardized recency, frequency and spend, the example produces three stable segments of four customers each, and the one-off large buyer belongs with the lapsed group rather than with the active one. A run that disagrees with that membership, or a silhouette search that proposes a cluster of one customer, is a signal to inspect the code before any segment reaches a campaign list.


··········


FOLLOW US FOR MORE.


·····


DATA STUDIOS


·····


datastudios.org


bottom of page