1

I have a column Name of string data type. I want to get all the values except the last one and put it in a new column FName, which I could achieve

df = pd.DataFrame({'Name': ['John A Sether', 'Robert D Junior', 'Jonny S Rab'], 
                        'Age':[32, 34, 36]})
df['FName'] = df['Name'].str.split(' ').str[0:-1]

              Name  Age        FName
0    John A Sether   32    [John, A]
1  Robert D Junior   34  [Robert, D]
2      Jonny S Rab   36   [Jonny, S]

But the new column FName looks like a list, which I don't want. I want it to be like: John A.

I tried convert the list to string, but it does not seems to be right. Any suggestion ?

1 Answer 1

4

You can use .str.rsplit:

df['FName'] = df['Name'].str.rsplit(n=1).str[0]

Or you can use .str.extract:

df['FName'] = df['Name'].str.extract(r'(\S+\s?\S*)', expand=False)

Or, you can chain .str.join after .str.split:

df['FName'] = df['Name'].str.split().str[:-1].str.join(' ')

              Name  Age     FName
0    John A Sether   32    John A
1  Robert D Junior   34  Robert D
2      Jonny S Rab   36   Jonny S
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.