Pandas中按列内数组长度删行?KeyError:0报错求解
问题解决方法
- 错误根源:原代码里
df['col'].df.len()是错误写法——Series对象不存在df属性,这种错误调用会触发KeyError。 - 两种正确实现方式:
- 通过
apply调用len函数判断数组长度:df = df.drop(df[df['col'].apply(len) != 100].index) - 使用pandas内置的
str.len()方法(适配序列中为可迭代对象的场景,比如列表、numpy数组):df = df.drop(df[df['col'].str.len() != 100].index)
- 通过
- 更简洁的替代写法(直接用布尔索引过滤):
df = df[df['col'].apply(len) == 100]
内容的提问来源于stack exchange,提问作者rebrid
相关产品推荐
相关产品推荐

