You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas如何筛选出某列中非空列表所在的行?

解决Pandas中筛选列表列非空行的问题

先复现你的场景:

import pandas as pd
data = [('words', ['foo', 'bar', 'baz', 'foobar', 'helter', 'skelter']), 
        ('counts', [[1,2,3], [], [5,8], [13,21,34,55], [89], [] ]) ]
df = pd.DataFrame.from_items(data)
print(df)

输出:

words               counts
0     foo           [1, 2, 3]
1     bar                  []
2     baz             [5, 8]
3  foobar  [13, 21, 34, 55]
4  helter                [89]
5  skelter                 []

为什么直接用df['counts'] != []会报错?

当你尝试df['counts'] != []时,Pandas会把空列表[]当作一个长度为0的数组,试图和长度为6的counts Series做逐元素比较——这就导致了数组长度不匹配的错误(ValueError: Arrays were different lengths: 6 vs 0)。简单来说,Pandas没法直接把整个Series和空列表做元素级的比较,因为空列表没有元素可以对应到Series的每一行。

几种可行的解决办法

方法1:使用str.len()访问器

对于存储列表的对象类型Series,可以用str访问器获取每个列表的长度,再筛选长度大于0的行:

filtered_df = df[df['counts'].str.len() > 0]
print(filtered_df)

输出:

words               counts
0     foo           [1, 2, 3]
2     baz             [5, 8]
3  foobar  [13, 21, 34, 55]
4  helter                [89]

方法2:使用apply()判断列表非空

利用Python中空列表布尔值为False、非空列表为True的特性,用apply()逐行判断:

filtered_df = df[df['counts'].apply(bool)]
# 也可以用更明确的长度判断:
# filtered_df = df[df['counts'].apply(lambda x: len(x) > 0)]
print(filtered_df)

输出和上面一致。

方法3:使用map()方法

和apply()逻辑类似,map()也能对每个元素做布尔转换:

filtered_df = df[df['counts'].map(bool)]
print(filtered_df)

同样能得到正确的筛选结果。

这些方法都避开了直接和空列表比较的陷阱,能准确筛选出counts列列表非空的行。

内容的提问来源于stack exchange,提问作者dokondr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:07:05