Martan
Martan

Reputation: 605

Count Number of elements in string in pandas cell

My data look like this

>df
    Employee     Entries
0       A     abc,sed,yrs,sef
1       B       wes,det,fyd

I want to count how many words are there in each row for column 'entries'. So first row is 4, second one 3.

I tried

# Count Comma and add 1
df['Entries_Count'] = df.Entries.str.count(',')+1

Which would be okay I some rows were not empty.

So how do i count elements in each cell. Also this is not a list, but a string.

Upvotes: 2

Views: 3417

Answers (2)

rishabh.malhotra
rishabh.malhotra

Reputation: 57

Use can use lambda function as well:
df['Entries_Count'] = df['Entries'].apply(lambda x: x.count(',')+1)

Upvotes: 1

Chris
Chris

Reputation: 29742

Use pandas.Series.str.count with regex

  Employee          Entries
0        A  abc,sed,yrs,sef
1        B      wes,det,fyd
2        C          oneword # Added for a demonstration
3        D                  # Added for a demonstration
4        E              NaN # Added for a demonstration

df['Entries'].str.count('\w+')

Output:

0    4.0
1    3.0
2    1.0
3    0.0
4    NaN
Name: Entries, dtype: float64

You can add sum to get total count:

df['Entries'].str.count('\w+').sum()

Output:

8

Upvotes: 3

Related Questions