renny
renny

Reputation: 600

Count the numbers after each comma and also the number before first comma in python

I have a dataframe with multiple columns and one of the columns book_no has multiple numbers separated by comma. I want to count those and assign it to a columns called as total_books_by_each_user. Example:

data['book_no']
1,2,3,5,10,11

Any possible solution to do this?

I tried this, but didn't work.

data.book_no.count(",") + 1

book number is of object type.

Upvotes: 2

Views: 185

Answers (1)

yatu
yatu

Reputation: 88276

You're missing the str accessor, which allows you to apply string operations in a vectorized manner:

df.book_no.str.count(',').add(1)

0    3
1    3
Name: book_no, dtype: int64

Upvotes: 3

Related Questions