Split pandas column and add last element to a new column Split pandas column and add last element to a new column pandas pandas

Split pandas column and add last element to a new column


You need another str to access the last splits for every row, what you did was essentially try to index the series using a non-existent label:

In [31]:df['lastname'] = df['fullname'].str.split().str[-1]dfOut[31]:         fullname lastname0   martin master   master1    andreas test     test


If need create 2 new columns, use str.rsplit with parameter n=1. If need only last column, EdChum solution is better:

print (df)                fullname0          martin master1           andreas test2  andreas martin masterdf[['first_name','last_name']] = df['fullname'].str.rsplit(expand=True, n=1)print (df)                fullname      first_name last_name0          martin master          martin    master1           andreas test         andreas      test2  andreas martin master  andreas martin    master