gpt4 book ai didi

python - 具有列表值的列,在执行 str.len() 时消除空格

转载 作者:行者123 更新时间:2023-12-05 09:02:53 25 4
gpt4 key购买 nike

我有一列,其中值是字符串列表,即

输入:

df = pd.DataFrame({'Food': [[''], ['potato', 'carrot'], ['potato', '']]})

看起来像:

Food                     
['']
['potato', 'carrot']
['potato', '']

当我执行 df['Count'] = df['Food'].str.len() 时,我得到:

Food                     Count
[''] 1
['potato', 'carrot'] 2
['potato', ''] 2

但是,我想得到:

Food                     Count
[''] 0
['potato', 'carrot'] 2
['potato', ''] 1

最佳答案

您正在尝试获取非空字符串的数量:

df['Food'].apply(lambda lst: len([e for e in lst if e != '']))

关于python - 具有列表值的列,在执行 str.len() 时消除空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70658713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com