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 – Remove a word from a cell

I have column containing names. I want to remove the name and the ; where its marked as (Retired) or (retired) after the name. But the problem is, it does not appear in the same format. Sometimes the cell has multiple names and one name is retried. In another case the cell will have first name followed by retired then the last name.

Dataframe = df

Sample column values – Current state

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

Owner Name
George (Georgy) (Retired) Clooney
Meghan (retired) Markle
Harry Porter (Retired)
Hermione Granger; Harry Porter (Retired)
Ginny Weasley; Ron Weasley; Harry Porter (retired); Luna Lovegood

Sample column values – Future state

Owner Name
Null
Null
Null
Hermione Granger
Ginny Weasley; Ron Weasley; Luna Lovegood

I thought of using replace with "" but it does not work. Please. I would appreciate any directions.

>Solution :

split, filter, join again with groupby.agg:

df['Owner Name'] = (df['Owner Name']
 .str.split(';\s*', expand=True).stack()
 .loc[lambda s: ~s.str.contains('\(Retired\)', case=False)]
 .groupby(level=0).agg('; '.join)
)

Output:

                                  Owner Name
0                                        NaN
1                                        NaN
2                                        NaN
3                           Hermione Granger
4  Ginny Weasley; Ron Weasley; Luna Lovegood
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