Nacho
Nacho

Reputation: 31

How to filter dataframe row based on length of column values

I have a dataframe with one column containing the following strings:

df=pd.DataFrame(['Hello world', 'World is good', 'Worldisnice hello'], columns=['A'])

df
                     A
0         'Hello world'
1       'World is good'
2   'Worldisnice hello'


I'm trying to get the rows that contain one word with 11 characters of length

I'm using the following code by it is giving me the length of the string and not the word inside the column

df = df[df['A'].apply(lambda x: len(x) == 11)]

Getting the following result:

df
                     A
0         'Hello world'

And the output should be:

df
                     A
0   'Worldisnice hello'

Since is the only one that contains one word with length equals to 11 characters

Thank you

Upvotes: 3

Views: 1663

Answers (3)

alec_djinn
alec_djinn

Reputation: 10789

I like to explicitly define simple filtering functions. I find it way more readable and maintainable.

In [8]: def f(row):
   ...:     words = row.A.split()
   ...:     for w in words:
   ...:         if len(w) == 11:
   ...:             return True
   ...: 

In [9]: df.loc[df.apply(f, axis=1) == True]
Out[9]: 
                   A
2  Worldisnice hello

Upvotes: 1

PieCot
PieCot

Reputation: 3639

Another approach:

df[df.A.str.split().map(lambda x: any(len(y) == 11 for y in x))]

that provides:

                   A
2  Worldisnice hello

Upvotes: 1

Danail Petrov
Danail Petrov

Reputation: 1875

len(x) in your code is checking the len of the entire string.

>>> df.A.str.len()
 0    11
 1    13
 2    17

What you need to do instead is to split the string into words and check if any of the words' length is == 11.

The following code is what should do the job.

>>> df[df['A'].apply(lambda x: any(len(y) == 11 for y in x.split()))]
                  A
2  Worldisnice hello

Upvotes: 2

Related Questions