regular expressions to remove parts of string of column starting with a digit

Viewed 32

I am trying to replace the parts of string of a dataframe column. Here is the dataframe below:

patientunitstayid,drugname    
144252,1000 ML  -  SODIUM CHLORIDE 0.9 % IV SOLN
142308,3 ML VIAL : INSULIN REGULAR HUMAN 100 UNIT/ML IJ SOLN

I want to replace the string which starts with digit and ends with '- ' or ': '. Basically want to extract 'SODIUM CHLORIDE' and 'INSULIN REGULAR HUMAN'. So, I tried this, but didnot work..

medications['drugname'] =  medications['drugname'].apply(lambda x: re.sub('^\d.*-\s\s$','', str(x)))
1 Answers

I think you want this regular expression:

from re import compile
mednamere = compile(r"\d*.*,\d*.*(?:-|:)\s+(.*)\s+\d.*")

#Testing with your examples:
test1 = "144252,1000 ML  -  SODIUM CHLORIDE 0.9 % IV SOLN"
test2 = "142308,3 ML VIAL : INSULIN REGULAR HUMAN 100 UNIT/ML IJ SOLN"
print(mednamere.findall(test1)[0])
print(mednamere.findall(test2)[0])
Related