简体   繁体   中英

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.

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.

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

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM