top bantz
top bantz

Reputation: 615

Creating a new data frame column, by splitting a string in another column in pandas

I'm trying to break down some data I have in a data frame, that looks like this for example:

Index   Name
0       joe bloggs
1       jane doe
2       first last

I want to create a new column, with just the last name for example.

I feel like I should be doing something along the lines of df['New_name'] = df['Name'].split() but I know that won't work.

Any help would be really appreciated, cheers

Upvotes: 0

Views: 312

Answers (3)

Acccumulation
Acccumulation

Reputation: 3591

df['New_name'] = df['Name'].str.split(expand =True)[1] gets the second word. If you want to make sure you get the last word, df['New_name'] = df['Name'].apply(lambda x: x.split()[-1]) works.

Upvotes: 1

Chris Adams
Chris Adams

Reputation: 18647

This should also do the trick:

df['Name'].str.split(' ').str[-1]

0    bloggs
1       doe
2      last

Upvotes: 1

G. Anderson
G. Anderson

Reputation: 5955

String handling in pandas series is a little weird. How about

df1['firstname'],df1['lastname']=df1['name'].str.split().str

Upvotes: 1

Related Questions