How could I title all words except the ones in the list, keep?
JavaScript
x
8
1
keep = ['for', 'any', 'a', 'vs']
2
df.col
3
``
4
0 1. The start for one
5
1 2. Today's world any
6
2 3. Today's world vs. yesterday.
7
8
Expected Output:
JavaScript
1
7
1
number title
2
0 1 The Start for One
3
1 2 Today's World any
4
2 3 Today's World vs. Yesterday.
5
6
7
I tried
JavaScript
1
2
1
df['col'] = df.col.str.title().mask(~clean['col'].isin(keep))
2
Advertisement
Answer
Here is one way of doing with str.replace
and passing the replacement function:
JavaScript
1
8
1
def replace(match):
2
word = match.group(1)
3
if word not in keep:
4
return word.title()
5
return word
6
7
df['title'] = df['title'].str.replace(r'(w+)', replace)
8
JavaScript
1
5
1
number title
2
0 1 The Start for One
3
1 2 Today'S World any
4
2 3 Today'S World vs. Yesterday.
5