Transforming full names to surname and initial I have a large data frame that I want to merge with another dataset. In order to do so I need to get the names of individuals into a certain format. The function below converts the name in 'column' to the desired format (mostly) and stores it in newColumn.

My question is, is there a better (faster and/or more pythonic) way to do this?

The main aim is to transform full names into surname and initials, such as:


Novak Djokovic = Djokovic N.
Jo-Wilfred Tsonga = Tsonga J.W.
Victor Estrella Burgos = Estrella Burgos V.
Juan Martin Del Potro = Del Potro J.M.




def convertNames(df,column, newColumn):
    df[newColumn] = 'none'

    for player in df[column]:

        names = player.split(' ')

        if len(names) == 2:

            if (len(names[0].split('-')) &gt; 1):
                newName = names[1]+' '+names[0].split('-')[0][0]+'.'+names[0].split('-')[1][0]+'.'
            else:
                newName = names[1]+' '+names[0][0]+'.'

        elif len(names) == 3:
            newName = names[1]+' '+names[2]+' '+names[0][0]+'.'

        else:
            newName = names[2]+' '+names[3]+' '+names[0][0]+'.'+names[1][0]+'.'

        df[newColumn][df[column] == player] = newName

    return df
You are doing way too much split()-ing.  You split on ‘-‘, and if you find the length of the split is greater than 1, you split on the ‘-‘ twice more, to get the first and the second part of the hyphenated name.  Split once, and save the result in a list, and access the list elements!

You are doing too much in convertNames().  It would be better to create a convertName() method, which just processes the player name into the desired form.  Then you could call that method from convertNames().

def convertName(player):
    names = player.split(' ')

    if len(names) == 2:
        names[0:1] = names[0].split('-', 1)

    surname = min(len(names)-1, 2)

    return ' '.join(names[surname:]) + ' ' + ''.join(name[0]+'.' for name in names[:surname])

# Test data
for player in ('Novak Djorkovic', 'Jo-Wilferd Tsonga', 'Victor Estrella Burgos', 'Juan Martin Del Potro'):
    print(player, ':', convertName(player))