如何根据条目的长度过滤 pandas 数据框 [英] How to filter a pandas dataframe based on the length of a entry

查看:48
本文介绍了如何根据条目的长度过滤 pandas 数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在大熊猫数据框中,我有一个字段"amp",该字段应由长度为495的列表填充.是否有一种熊猫式方法可快速对此长度进行过滤,以使所有具有字段"amp"的行都不会等于495掉了?

In a pandas dataframe I have a field 'amp' that should be populated by a list of length 495. Is there a panda-ic way to quickly filter on this length, such that all rows with field 'amp' are not equal to 495 are dropped?

我尝试过

df[len(df['amp']) == 495]

这又返回了

KeyError: False

谢谢.

推荐答案

如果您特别需要len,那么@MaxU的答案是最好的.

If you specifically need len, then @MaxU's answer is best.

有关更通用的解决方案,您可以使用系列的地图方法.

For a more general solution, you can use the map method of a Series.

df[df['amp'].map(len) == 495]

这会将len应用于每个元素,这就是您想要的.使用此方法,您可以使用任何任意函数,而不仅仅是len.

This will apply len to each element, which is what you want. With this method, you can use any arbitrary function, not just len.

这篇关于如何根据条目的长度过滤 pandas 数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆