Extract first and last words from strings as a new column in pandas

Viewed 4110

I am struggling to create two new columns based on string in another column.

what I have

     Profile
0    Technician
1    Service Engineer
2    Sales and Service Support Engineer

what I like to have

     First              Last
0    Technician         NaN
1    Service            Engineer
2    Sales              Engineer

My attempt was to use solutions like

new = tl['Profile'].str.split(' ')
tl['First'] = new[0]
tl['Last'] = new[1]

But this is correct only for First.

2 Answers

Let's try str.extract here:

df['Profile'].str.extract(r'^(?P<First>\S+).*?(?P<Last>\S+)?$')

        First      Last
0  Technician       NaN
1     Service  Engineer
2       Sales  Engineer

Not many str methods will be as elegant as this because of the additional need to handle sentences with one word only.


You can also use str.partition here.

u = df['Profile'].str.partition()
pd.DataFrame({'First': u[0], 'Last': u[2].str.split().str[-1]})

        First      Last
0  Technician       NaN
1     Service  Engineer
2       Sales  Engineer

Without regex, using loops

For last name

k=[]
for i in df_names_test['Name']:
    h=len(i.split(" "))
    j=i.split(" ")[h-1]
    k.append(j)


df_names_test["Last"]=k

for first name

k=[]
for i in df_names_test['Name']:

    j=i.split(" ")[0]
    k.append(j)


df_names_test["First"]=k

Using Lambda functions: First name

df_names_test['First']=df_names_test['Name'].apply(lambda x: x.split(" ")[0])

Last name:

df_names_test['Last']=df_names_test['Name'].apply(lambda x: x.split(" ")[-1])
Related