Removing last words in each row in pandas dataframe

Question:

A dataframe contains a column named ‘full_name’ and the rows look like this:

full_name 
Peter Eli Smith 
Vanessa Mary Ellen 
Raul Gonzales 
Kristine S Lee 

How do I remove the last words and add an additional column called ‘first_middle_name’ which will result like this?:

full_name          first_middle_name
Peter Eli Smith    Peter Eli 
Vanessa Mary Ellen Vanessa Mary 
Raul Gonzales      Raul 
Kristine S Lee     Kristine S 

Thank you

Asked By: musik lover

||

Answers:

We can try using str.replace here:

df["first_middle_name"] = df["full_name"].replace("s+S+$", "")

See the above regex replacement working in the demo link below.

Demo

Answered By: Tim Biegeleisen

Use str

df["first_middle_name"] = df["full_name"].str.replace("s+S+$", "")
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.