-2

I need to swap the list of names which is in the format of FirstName and LastName which in a dataframe one column, using python.

Below is the sample format: ~Adam Smith

The above need to change into ~Smith Adam

Is there any single line function available in python?

Could anyone help on this!!

3
  • 2
    This is a trivial task. What did you try? Please include your code. Commented Jul 19, 2018 at 6:56
  • print( " ".join(reversed("Adam Smith".split()))) Commented Jul 19, 2018 at 6:58
  • df.name.str.split().apply(lambda x: ' '.join(x[::-1])) Commented Jul 19, 2018 at 6:59

1 Answer 1

1

Using apply

import pandas as pd
df = pd.DataFrame({"names": ["Adam Smith", "Greg Rogers"]})
df["names"] = df["names"].apply(lambda x: " ".join(reversed(x.split()))) 
print(df)

Output:

         names
0   Smith Adam
1  Rogers Greg
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot. It works
You are welcome
I need a help on string manipulation on dataframes

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.