Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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))
like image 895
asd Avatar asked Feb 24 '21 10:02

asd


1 Answers

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.
like image 104
Shubham Sharma Avatar answered Oct 04 '22 22:10

Shubham Sharma