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 a character every nth character in a pandas dataframe column

One column of my dataframe contains mac addresses without colons.
I would like to add a colon to every mac address after every 2nd character.

I was looking for a split every nth character option of pd.Series.split.str() so that I could split the mac address in six and concat afterwards but according to the documentation splitting on number of characters is not available. There is the regex option, but regex is not a skill I have.

I assume there is an even easier solution than splitting and concatting but I have not come across that.

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

Help would be much appreciated, thank you.

      mac_address
0     0003E6A584C2
1     0003E6A584CC
2     0003E6A584DA
3     0003E6A584DC
4     0003E6A584E4

>Solution :

Let us try findall with map (.. means N = 2)

df.mac_address.str.findall('..').map(';'.join)
Out[368]: 
0    00;03;E6;A5;84;C2
1    00;03;E6;A5;84;CC
2    00;03;E6;A5;84;DA
3    00;03;E6;A5;84;DC
4    00;03;E6;A5;84;E4
Name: mac_address, dtype: object
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