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

pandas: split a column on multiple words present in all cells

I would like to split the column in this dataframe on name into two columns,

import pandas as pd
import re
df1 = pd.DataFrame({'Name': ['Steve _ (ICANA) Smith', 'Joe _ (ICANA) Nadal',
                       'Roger _ (ICANA) Federer_blu']})

My desired output would be:

                          Name  First    Last
0        Steve _ (ICANA) Smith  Steve    Smith
1          Joe _ (ICANA) Nadal  Joe      Nadal
2  Roger _ (ICANA) Federer_blu  Roger    Federer_blu

so I would like to get rid of ‘ _ (ICANA)’. using split, I have done,

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

df1[['First','last']] = df1.Name.str.split(r"\b _ (ICANA)\b", expand=True)

which returns the following error,

ValueError: Columns must be same length as key

>Solution :

You regex was incorrect, you need to escape the parentheses:

df1[['First','last']] = df1.Name.str.split(r"\s*_ \(ICANA\)\s*", expand=True)

However, to avoid any issue, the best remains to use extract, which will ensure a fixed number of output columns:

df1[['First','last']] = df1.Name.str.extract(r'(\w*)\s*_ \(ICANA\)\s*(\w*)')
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