Skip to content
Advertisement

Title words in a column except certain words

How could I title all words except the ones in the list, keep?

keep = ['for', 'any', 'a', 'vs']
df.col
 ``         
0    1. The start for one
1    2. Today's world any
2    3. Today's world vs. yesterday.

Expected Output:

     number   title
0     1       The Start for One
1     2       Today's World any
2     3       Today's World vs. Yesterday.


I tried

df['col'] = df.col.str.title().mask(~clean['col'].isin(keep))

Advertisement

Answer

Here is one way of doing with str.replace and passing the replacement function:

def replace(match):
    word = match.group(1)
    if word not in keep:
        return word.title()
    return word

df['title'] = df['title'].str.replace(r'(w+)', replace)

   number                         title
0       1             The Start for One
1       2             Today'S World any
2       3  Today'S World vs. Yesterday.
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement