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 split value in dataframe and replace with another value

dataframe

import pandas as pd
d = {'A': ['B_502_ZZZ_01', 'B_400__01']}
df = pd.DataFrame(data=d)

I tried

def f(x):
 x = x.split('_')[2]
 if x=='':
   x = x.replace('', 'ZZZ') 
 return x
else: 
 return x
df['A'].apply(f)

output required full value like not only 2nd position. I can split 3rd position in another column but I want position changes at that location directly.

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

['B_502_ZZZ_01', 'B_400_ZZZ_01'] 

>Solution :

You can use a regex:

df['A'] = df['A'].str.replace(r'((?:[^_]+_){2})(?=_)', r'\1ZZZ', regex=True)

NB. The 2 in the regex indicates the number of _ after which to perform the replacement

output (as new column A2 for clarity):

              A            A2
0  B_502_ZZZ_01  B_502_ZZZ_01
1     B_400__01  B_400_ZZZ_01

regex demo

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