shan
shan

Reputation: 583

Counting of elements in list not producing expected result

I have a pandas dataframe dftouse['col a'] which consists of lists :

0        []                            
1        [carbon, nature]              
2        [Lincoln]                     
3        [CBDC]                        
4        [] 

I want to count elements in each list across the rows. When I am executing

dftouse['Col a'].apply(lambda x: (len(x)-1) if not x else len(x))

0        1
1        2
2        1
3        1
4        1

Expected :

0        0
1        2
2        1
3        1
4        0

It would be helpful if I can get help debugging this. TIA

Upvotes: 0

Views: 35

Answers (2)

Sruthi
Sruthi

Reputation: 3018

You can also use str.len() on the column

>>> dftouse['col a'].str.len()
0    0
1    2
2    1
3    1
4    0
Name: col a, dtype: int64

Upvotes: 0

Corralien
Corralien

Reputation: 120499

Use len on apply:

>>> dftouse['Col a'].apply(len)

0    0
1    2
2    1
3    1
4    0
Name: Col a, dtype: int64

Upvotes: 1

Related Questions