简体   繁体   中英

str.contains only and exact value

I have the following list :

personnages = ['Stanley','Kevin', 'Franck']

I want to use str.contains function to create a new pandas dataframe df3 :

df3 = df2[df2['speaker'].str.contains('|'.join(personnages))]

However, if the row of the column speaker contains : 'Stanley & Kevin', i don't want it in df3.

How can I improve my code to do this ?

Here what I would do:

# toy data
df =  pd.DataFrame({'speaker':['Stanley & Kevin', 'Everybody', 
                               'Kevin speaks', 'The speaker is Franck', 'Nobody']})

personnages = ['Stanley','Kevin', 'Franck']

pattern = '|'.join(personnages)
s = (df['speaker'].str
       .extractall(f'({pattern})')  # extract all personnages
       .groupby(level=0)[0]         # group by df's row
       .nunique().eq(1)             # count the unique number
    )
df.loc[s.index[s]]

Output:

                 speaker
2           Kevin speaks
3  The speaker is Franck

You'll want to denote line start and end in your regex, that way it only contains the single name:

import pandas as pd

speakers = ['Stanley', 'Kevin', 'Frank', 'Kevin & Frank']
df = pd.DataFrame([{'speaker': speaker} for speaker in speakers])
         speaker
0        Stanley
1          Kevin
2          Frank
3  Kevin & Frank


r = '|'.join(speakers[:-1]) # gets all but the last one for the sake of example

# the ^ marks start of string, and $ is the end
df[df['speaker'].str.contains(f'^({r})$')]
   speaker
0  Stanley
1    Kevin
2    Frank

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