Skip to content Skip to sidebar Skip to footer

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 fiel

Solution 1:

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.

Solution 2:

Try this:

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

Demo:

In[77]: dfOut[77]:
                 a0[1, 2, 3, 4, 5]1[1, 2, 3]2[-1]In[78]: df.a.str.len()
Out[78]:
051321Name: a, dtype: int64In[79]: df[df.a.str.len() == 3]Out[79]:
                 a1[1, 2, 3]

Post a Comment for "How To Filter A Pandas Dataframe Based On The Length Of A Entry"