Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

I have a pandas DataFrame and I want to delete rows from it where the length of the string in a particular column is greater than 2.

I expect to be able to do this:

df[(len(df['column name']) < 2)]

but I just get the error:

KeyError: u'no item named False'

What am I doing wrong?

(Note: I know I can use df.dropna() to get rid of rows that contain any NaN, but I didn't see how to remove rows based on a conditional expression.)

1 Answer

0 votes
by (106k points)

To delete rows from a pandas DataFrame based on a conditional expression involving len(string) giving KeyError you can do len(df['column name']) you are just getting one number, namely the number of rows in the DataFrame (i.e., the length of the column itself). If you want to apply len to each element in the column, use df['column name'].map(len)

You can try a below-mentioned piece of code:-

df[df['column name'].map(len) < 2]

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...