2

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.

2 Answers 2

2

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
1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.