简体   繁体   中英

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM