Search code examples
pythonpandasdrop

Dropping every row with len >2 Pandas python


Suppose I have a dataframe

. Values
0  25
1  897
2  48 
3  28
4  214
5  25

I am trying to drop all rows with len > 2 with the following code but nothing happens when I run it.

import pandas as pd
df = pd.read_csv('File.csv')

for index in df.index:
    if len(df.loc[index, 'Sevens']) > 2:
        df.drop([index])
    else:
        pass

Solution

  • Use Series.str.len in boolean indexing:

    df1 = df[df['Value'].str.len() <=2]
    

    If values was numbers:

    df1 = df[df['Value'].astype(str).str.len() <=2]