Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting number of values in each cluster in KMeans Algorithm

How to get the total number of values in each clusters in KMeans Algorithm in Pandas ?

I tried the following:

kmeans_model = KMeans(n_clusters = 3, random_state = 1).fit(dataframe.iloc[:,:])
clusters = kmeans_model.labels_.count()

but it is not working.

My expected output is like:

Clusters   Number_of_values
cluster_0  932
cluster_1  931
cluster_2  930

Any idea how can I achieve this in Pandas ?

I tried this also, it works. It would be better if I have any other option.

from collections import Counter
print(Counter(kmeans_model.labels_))

Thanks in advance.

like image 201
JSVJ Avatar asked Oct 28 '25 16:10

JSVJ


1 Answers

you can do this

add column for cluster numbers to the dataframe

kmeans_model = KMeans(n_clusters = 3, random_state = 1).fit(dataframe)

dataframe['kmean'] = kmeans_model.labels_

then count them

dataframe['kmean'].value_counts()
like image 73
M_S_N Avatar answered Oct 31 '25 07:10

M_S_N



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!