Separate the pandas column and add the last item to the new column

I have a pandas framework containing (among other columns) full names:

 fullname
 martin master
 andreas test

I want to create a new column that splits the column of the full name along the space and assigns the last element to the new column. The result should look like this:

 fullname           lastname
 martin master      master
 andreas test       test

I thought it would work like this:

df['lastname'] = df['fullname'].str.split(' ')[-1]

However i get KeyError: -1

I use [-1], that is, the last element of the divided group, to make sure that I get the real last name. In some cases (for example, a name of the type andreas martin master) this helps to get the last name, that is, the master.

So how can I do this?

+4
source share
2 answers

str, , , , :

In [31]:

df['lastname'] = df['fullname'].str.split().str[-1]
df
Out[31]:
         fullname lastname
0   martin master   master
1    andreas test     test
+5

2 , str.rsplit n=1. , EdChum :

print (df)
                fullname
0          martin master
1           andreas test
2  andreas martin master

df[['first_name','last_name']] = df['fullname'].str.rsplit(expand=True, n=1)
print (df)
                fullname      first_name last_name
0          martin master          martin    master
1           andreas test         andreas      test
2  andreas martin master  andreas martin    master
+1

Source: https://habr.com/ru/post/1648624/


All Articles