Reputation: 2691
I want to calculate the count of how many names there are included in the the column of dataframe in Python.
I get the column names from dataframe as defined command
df["Names_Column"]
Here is the values of one column in dataframe
Names_Column
Damandeep Singh Baggan, Smita Malhotra, Baba Sehgal, Deepak Chachra
Damandeep Singh Baggan, Smita Malhotra, Deepak Chachra
...
I want to get a result of a count like this.
Name Count
Damandeep Singh Baggan 4
Deepak Chachra 3
Smita Malhotra 2
...
I can try to this code to seperate names but I couldn't do it.
separate = df["Names_Column"].str.split(",")
How can I do it?
Upvotes: 0
Views: 359
Reputation: 4736
Combining explode
, and value_counts
on the column solves this problem.
import pandas as pd
df = pd.DataFrame([
['Damandeep Singh Baggan, Smita Malhotra, Baba Sehgal, Deepak Chachra'],
['Damandeep Singh Baggan, Smita Malhotra, Deepak Chachra']],columns=['Names_Column'])
df2 = df.apply(lambda x: x.str.split(', ').explode())
df2['Names_Column'].value_counts()
returns
count
Names_Column
Baba Sehgal 1
Damandeep Singh Baggan 2
Deepak Chachra 2
Smita Malhotra 2
Upvotes: 1