The Nightman
The Nightman

Reputation: 5759

Check if string within strings in pandas DataFrame column

I have a pretty simple pandas DataFrame and I want to select the portion of the DataFrame that has data within a column that contains within it another string

So if this is my DataFrame and I want those columns that contain some within the Loc column how can this be done?

             Loc 
0      'something'  
1      'nothing'  

I tried two things:

df['some' in df['Loc']]
df[df.Loc.contains('some')]

But neither solution works.

Upvotes: 2

Views: 13119

Answers (3)

BENY
BENY

Reputation: 323226

Using replace , a fun way

df[df.Loc.replace({'some':np.nan},regex=True).isnull()]
Out[787]: 
           Loc
0  'something'

Update since Alex mention it in comment

df[df.Loc.apply(lambda x : 'some' in x)]
Out[801]: 
           Loc
0  'something'

Upvotes: 1

Alexander
Alexander

Reputation: 109526

You need to use contains, one of the string accessor methods.

>>> df['Loc'].str.contains('some')
0     True
1    False
Name: Loc, dtype: bool

One would then use boolean indexing on the result to select the relevant rows of your dataframe.

Upvotes: 6

Windyground
Windyground

Reputation: 119

df[df['Loc'].str.contains('some')]

Upvotes: 3

Related Questions