belewis6i
belewis6i

Reputation: 97

Extract last word in DataFrame column

This has to be so simple - but I can't figure it out. I have a "name" column within a DataFrame and I'm trying to reverse the order of ['First Name', 'Middle Name', 'Last Name'] to ['Last Name', 'First Name', 'Middle Name'].

Here is my code:

for i in range(2114):
bb = a['Approved by User'][i].split(" ",2)[2]
aa = a['Approved by User'][i].split(" ",2)[0]
a['Full Name]'] = bb+','+aa

Unfortunately I keep getting IndexError: list index out of range with the current code.

This is what I want:

Old column Name| Jessica Mary Simpson

New column Name| Simpson Jessica Mary

Upvotes: 2

Views: 1245

Answers (3)

RavinderSingh13
RavinderSingh13

Reputation: 133518

With your shown samples, you could try following. Let's say following is the df:

    fullname
0   Jessica Mary Simpson
1   Ravinder avtar singh
2   John jonny janardan

Here is the code:

df['fullname'].replace(r'^([^ ]*) ([^ ]*) (.*)$', r'\3 \1 \2',regex=True)

OR

df['fullname'].replace(r'^(\S*) (\S*) (.*)$', r'\3 \1 \2',regex=True)

output will be as follows:

0   Simpson Jessica Mary
1   singh Ravinder avtar
2   janardan John jonny

Upvotes: 2

jezrael
jezrael

Reputation: 862651

I think problem is in your data, here is your solution in pandas text functions Series.str.split, indexing and Series.str.join:

df['Full Name'] = df['Approved by User'].str.split(n=2).str[::-1].str.join(' ')
print (df)
       Approved by User             Full Name
0  Jessica Mary Simpson  Simpson Mary Jessica
1              John Doe              Doe John
2                  Mary                  Mary

Upvotes: 1

The.B
The.B

Reputation: 381

One way to do it is to split the string and joinit later on in a function. like so:

import pandas as pd

d = {"name": ["Jessica Mary Simpson"]}

df = pd.DataFrame(d)
a = df.name.str.split()
a = a.apply(lambda x: " ".join(x[::-1])).reset_index()
print(a)

output:

    index   name
0   0   Simpson Mary Jessica

Upvotes: 2

Related Questions