Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

python - 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

question from:https://stackoverflow.com/questions/65641687/how-to-filter-dataframe-row-based-on-length-of-column-values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...