jajoyko98
jajoyko98

Reputation: 11

Calculate length of list pandas dataframe where cell value is a list

Given such a data frame df:

id     elements
1     Ba, Ca
2     Th
3     Ag, Au, Ca, Mg, V
4     Au, Ca

I would like to calculate a column that has the number of items in the elements list. For example:

id    elements             count
1     Ba, Ca               2
2     Th                   1
3     Ag, Au, Ca, Mg, V    5
4     Au, Ca               2

Any ideas on how to solve this issue would be greatly appreciated.

Upvotes: 1

Views: 66

Answers (1)

BENY
BENY

Reputation: 323276

Let us try count the sep

df['ct']=df.elements.str.count(',')+1

Upvotes: 1

Related Questions