Dan Steingart Dan Steingart - 1 year ago 140
Python Question

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download