I wrote this code.
It works, but I think there is a more elegant and Pythonic way to this task.
- Groupby and count the different occurences
- Get the sum of all the occurences
Divide each occurrence by the total of the occurrences and get the percentage
#Creating the dataframe ##The cluster column represent centroid labels of a clustering alghoritm df=pd.DataFrame({'char':['a','b','c','d','e'], 'cluster':[1,1,2,2,2]}) #Counting the frequency of each labels cluster_count=df.groupby('cluster').count() #Calculating the sum of the frequency cluster_sum=cluster_count.sum() #Normalizing the frequency cluster_prct=cluster_count.char.apply(lambda x: 100*x/cluster_sum) print(cluster_prct)
Output:
cluster
1 40.0
2 60.0
print(cluster_prct)
. I edited the question. \$\endgroup\$