Home > Software design >  Python: Split using lambda and keeping second value
Python: Split using lambda and keeping second value

Time:07-07

I have the following df:

pd.DataFrame({'Jugador': {0: 'A. Gignac', 1: 'N. Ibáñez'},
              'Equipo': {0: 'Tigres UANL', 1: 'Pachuca'},
              'Equipo durante el período seleccionado': {0: 'Tigres UANL', 1: 
              'Pachuca'})

I am trying to split the Jugador column and only keeping the last name by using the following code:

df.Jugador.apply(lambda name: name.split(' ')[1])

when I run the code I get the following error:

IndexError: list index out of range

Expected output:

pd.DataFrame({'Jugador': {0: 'Gignac', 1: 'Ibáñez'},
          'Equipo': {0: 'Tigres UANL', 1: 'Pachuca'},
          'Equipo durante el período seleccionado': {0: 'Tigres UANL', 1: 
          'Pachuca'})

CodePudding user response:

The error is causing as you are trying to find the 1 index of the whole name. If there is no any surname, 1 index will be out of range. So, it is the reason for the error.

Try this:

df.Jugador = df.Jugador.apply(lambda name: name.split(' ')[-1])
  • Related