简体   繁体   中英

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.

Let us try count the sep

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM