Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas .title() when string has an 's

Tags:

python

pandas

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()

enter image description here

like image 996
John Avatar asked Mar 21 '26 15:03

John


2 Answers

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)
like image 134
lemon Avatar answered Mar 23 '26 10:03

lemon


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"))
like image 32
Ynjxsjmh Avatar answered Mar 23 '26 09:03

Ynjxsjmh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!