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

How to insert character ('-") every time my string changes from text to number and vice versa?

This is an example of a bigger dataframe. Imagine I have a dataframe like this:

import pandas as pd

df = pd.DataFrame({"ID":["4SSS50FX","2TT1897FA"],
                   "VALUE":[13, 56]})

df
Out[2]: 
          ID  VALUE
0   4SSS50FX     13
1  2TT1897FA     56

I would like to insert "-" in the strings from df["ID"] everytime it changes from number to text and from text to number. So the output should be like:

          ID  VALUE
0   4-SSS-50-FX     13
1  2-TT-1897-FA     56

I could create specific conditions for each case, but I would like to automate it for all the samples. Anyone could help me?

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 can use a regular expression with lookarounds.

df['ID'] = df['ID'].str.replace(r'(?<=\d)(?=[A-Z])|(?<=[A-Z])(?=\d)', '-')

The regexp matches an empty string that’s either preceded by a digit and followed by a letter, or vice versa. This empty string is then replaced with -.

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