rachelalll
rachelalll

Reputation: 122

Python Dataframes where string has a specified length

I am trying to get a pandas dataframe where the string name has 2 or more spaces. I have the following code, but I was wondering if there was another way to do it?

df[len(df['name'].str.split()) >=3]

Upvotes: 0

Views: 29

Answers (1)

anky
anky

Reputation: 75080

you can try series.str.count here:

n_or_more_spaces = 2
df[df['name'].str.count(' ') >= n_or_more_spaces]

Sample test:

s = pd.Series(['a b c','c d e f','gh'])
s[s.str.count(' ')>=2]

0      a b c
1    c d e f
dtype: object

Upvotes: 3

Related Questions