Dawn17
Dawn17

Reputation: 8297

Parsing row where its column has less than 4 characters

command description
0   A.B.C.D IPv4 Prefix entries to show
1   A.B.C.D/length  IPv4 Prefix mask
2   BVI Bridge-Group Virtual Interface
3   Bundle-Ether    Aggregated Ethernet interface(s) | short name ...
4   Bundle-POS  Aggregated POS interface(s) | short name is BP

I am trying to select the rows where the description is less than 4 chars.

I tried

df.loc[len(df['description']) < 4]

but it's giving me a KeyError: False.

Any help?

Upvotes: 1

Views: 47

Answers (2)

Ankur Sinha
Ankur Sinha

Reputation: 6669

While jerzrael's answer is simple and straightforward, I will add another alternative where you can count the characters in the string. Since your column has ASCII characters, you can use [\x00-\x7F] for a match. Like this:

df[df.description.str.count('[\x00-\x7F]') < 4]

In case let's say you want to count the occurences of a specific character, you can replace it with that character, for example let's say A.

df[df.description.str.count('A') < 4]

Upvotes: 1

jezrael
jezrael

Reputation: 863226

Use Series.str.len with boolean indexing, so loc is not necessary:

df[df['description'].str.len() < 4]

Upvotes: 3

Related Questions