Title words in a column except certain words
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.
First we create your number
and title
column. Then we use Series.explode
to get a word per row. If the word is in keep
we ignore it, else apply Series.str.title
:
keep = ['for', 'any', 'a', 'vs']
# create 'number' and 'title' column
df[['number', 'title']] = df['col'].str.split(".", expand=True, n=1)
df = df.drop(columns='col')
# apply str.title if not in keep
words = df['title'].str.split().explode()
words = words.str.replace(".", "", regex=False)
words = words.mask(words.isin(keep)).str.title().fillna(words)
df['title'] = words.groupby(level=0).agg(" ".join)
Output
number title
0 1 The Start for One
1 2 Today'S World any
2 3 Today'S World vs. Yesterday.