Here is the code and output :
kmeans_model = KMeans(n_clusters=k, init='k-means++', random_state=42, n_init=10)
mall_customers_data['Cluster'] = kmeans_model.fit_predict(X)
# Get the cluster centroids
centroids = kmeans_model.cluster_centers_
# --- Step 3: Visualize the clustered graph ---
plt.figure(figsize=(12, 8))
sns.scatterplot(data=mall_customers_data, x='Annual_Income_(k$)', y='Spending_Score',
hue='Cluster', palette='viridis', s=100, alpha=0.8, legend='full')
# Plot the centroids
plt.scatter(centroids[:, 0], centroids[:, 1], s=300, c='red', marker='X', edgecolor='black', label='Centroids')
plt.title('Customer Segments (K-Means Clustering)', fontsize=16)
plt.xlabel('Annual Income (k$)', fontsize=12)
plt.ylabel('Spending Score (1-99)', fontsize=12)
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
plt.grid(True, linestyle='--', alpha=0.7)
plt.tight_layout()
plt.show()
print("\nFirst 5 rows of the DataFrame with new 'Cluster' column:")
display(mall_customers_data.head())