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

Python pandas regex extract to 4 new columns

import pandas as pd
df = pd.DataFrame(data={'data': ['2 (B) - 15 (K)']})
print(df)

Current DataFrame:

             data
0  2 (B) - 15 (K)

What am looking to do is to extract 2, B, 15 and K into 4 new columns within the same dataframe.

is that possible using pandas.regex 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

>Solution :

With the same pattern spaces-parenthesis-dash and empty strings, this way works

df = pd.DataFrame(data={'data': ['2 (B) - 15 (K)', '']})
print(df['data'].str.extract('(\d*).\((.)\).-.(\d*).\((.)\)'))
#      0    1    2    3
# 0    2    B   15    K
# 1  NaN  NaN  NaN  NaN
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