Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

python - How to filter a pandas dataframe based on the length of a entry

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?

I tried

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

and this returned

KeyError: False

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...