I converted a string in a Pandas dataframe to title case. However, when I do, anything directly after an apostrophe becomes uppercase as well. How do I correct this?
df[cols] = df[cols].apply(lambda x: x.str.title())
df['name'] = df['name'].replace("\'S", "\'s")
df.head()
CodePudding user response:
If you want to avoid 'later fixing', one idea could be to split the string on the space and uppercase first letter of each word:
df[cols] = df[cols].applymap(
lambda string: ' '.join(map(str.capitalize, string.split()))
)
Following @shriakhilc interesting suggestion, there is also an equivalent built-in way of doing this with the string.capwords method:
from string import capwords
df[cols] = df[cols].applymap(capwords)
CodePudding user response:
You can try enable the regex
parameter
df['name'] = df['name'].replace("'S", "'s", regex=True)
Or use pandas.Series.str.replace
df['name'] = df['name'].str.replace("'S", "'s")
# To fix multiple columns
df[cols] = df[cols].apply(lambda col: col.str.replace("'S", "'s"))