Using Regex in Pandas to change case of captured string

Question:

I’m trying to capitalize the first letter after a parantheses in a dataframe column.

This is the closest I got but I don’t know how to actually reference the string that is captured so I can apply .upper() method to it

df['item_name'] = df['item_name'].str.replace(r"(?<=[(])[a-z]", ###what to put?###.upper(), regex=True)
Asked By: spg719

||

Answers:

You ca pass a function as replacement value:

df['item_name'] = df['item_name'].str.replace(r"(?<=[(])[a-z]",
                                              lambda m: m.group().upper(),
                                              regex=True)

Example: vowels to uppercase.

df = pd.DataFrame({'A': ['abcde', 'fghij']})
df['B'] = df['A'].str.replace(r"[aeiou]", lambda m: m.group().upper(), regex=True)

output:

       A      B
0  abcde  AbcdE
1  fghij  fghIj
Answered By: mozway
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.