Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using Regex in Pandas to change case of captured string

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading