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

Extract from pattern if present, else keep as-is

Say I have the following series:

ser = pd.Series(['abc', '(d:affds)', 'trrt'])

If an element starts with (d:) and ends with ), I’d like to extract what’s inside. Else, I’d like to keep it as-is.

If I do

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

ser.str.extract(r'\(d:(.*)\)')

then I get

       0
0    NaN
1  affds
2    NaN

So, the extraction worked fine for row 1. However, for rows 0 and 2, I’d like to keep the row as-is. So, my expected output is:

       0
0    abc
1  affds
2   trrt

>Solution :

You may add fillna

ser.str.extract(r'\(d:(.*)\)')[0].fillna(ser)
Out[163]: 
0      abc
1    affds
2     trrt
Name: 0, 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