列表中元素的计数未产生预期结果

Counting of elements in list not producing expected result

我有一个 pandas 数据框 dftouse['col a'],它由列表组成:

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

我想跨行计算每个列表中的元素。当我执行

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

预期:

0        0
1        2
2        1
3        1
4        0

如果我能获得调试方面的帮助,那将会很有帮助。 TIA

apply 上使用 len:

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

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

您也可以在列

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