I have a pandas dataframe containing (besides other columns) full names:
fullname
martin master
andreas test
I want to create a new column which splits the fullname column along the blank space and assigns the last element to a new column. The result should look like:
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 a KeyError: -1
I use [-1]
, that is the last element of the split group, in order to be sure that I get the real last name. In some cases (e.g. a name like andreas martin master), this helps to get the last name, that is, master.
So how can I do this?