Search code examples
pythonpandasdataframesplitreverse

changing column data with "lastname, firstname" to "firstname lastname" in python pandas dataframe


I have python pandas dataframe, served up by power bi data source transformation support for execution of python script, where one of the columns consists of lastname, firstname and I need it to consist of firstname lastname.

I've tried the following split, reversed, join approach which works on a standalone string argument but generates AttributeError: 'Series' object has no attribute 'split' when I try it on column data in a pandas dataframe.

name = 'LastName, FirstName'
' '.join(reversed(name.split(', ')))
# output = 'FirstName LastName'

import pandas as pd
df = pd.DataFrame({'full_name': ['doe, john', 'smith, kate', 'jones, susan', 'edwards, jack' ],
                   'num_legs': [2, 4, 8, 0],
                   'num_wings': [2, 0, 0, 0],
                   'num_specimen_seen': [10, 2, 1, 8]},
                   index=['falcon', 'dog', 'spider', 'fish'])
df
df['full_name'] = ' '.join(reversed(df['full_name'].split(', ')))
# output = AttributeError: 'Series' object has no attribute 'split'

Searching SO i see hits for doing this something of this nature in an excel column and in a R list but nothing i have been able to find yet for column in a python pandas dataframe.


Solution

  • In your case we can do split with map PS : ::-1 here is reversed the order

    df.full_name=df.full_name.str.split(', ').map(lambda x : ' '.join(x[::-1]))
    df.full_name
    falcon        john doe
    dog         kate smith
    spider     susan jones
    fish      jack edwards
    Name: full_name, dtype: object