Home > other >  Counting of elements in list not producing expected result
Counting of elements in list not producing expected result

Time:12-06

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

CodePudding user response:

Use len on apply:

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

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

CodePudding user response:

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
  • Related