2

In python, I have the following df (headers in first row):

FullName          FirstName
'MichaelJordan'   'Michael'
'KobeBryant'      'Kobe'
'LeBronJames'     'LeBron'  

I am trying to split each record in "FullName" based on the value in "FirstName" but am not having luck...

This is what I tried:

df['Names'] = df['FullName'].str.split(df['FirstName'])

Which produces error:

'Series' objects are mutable, thus they cannot be hashed

Desired output:

print(df['Names'])

['Michael', 'Jordan']
['Kobe', 'Bryant']
['LeBron', 'James']

4 Answers4

5

str.replace

lastnames = [full.replace(first, '') for full, first in zip(df.FullName, df.FirstName)]
df.assign(LastName=lastnames)

        FullName FirstName LastName
0  MichaelJordan   Michael   Jordan
1     KobeBryant      Kobe   Bryant
2    LeBronJames    LeBron    James

Same exact idea but using map

df.assign(LastName=[*map(lambda a, b: a.replace(b, ''), df.FullName, df.FirstName)])

        FullName FirstName LastName
0  MichaelJordan   Michael   Jordan
1     KobeBryant      Kobe   Bryant
2    LeBronJames    LeBron    James
piRSquared
  • 240,659
  • 38
  • 359
  • 510
3

since you are making row wise operations we can use apply,

the idea is is to replace the first name with it self + a comma to split it by

df["SplitName"] = df.apply(
    lambda x: x["FullName"].replace(x["FirstName"], f"{x['FirstName']}, "), axis=1
)


print(df['SplitName'].str.split(',',expand=True))

         0        1
0  Michael   Jordan
1     Kobe   Bryant
2   LeBron    James
Umar.H
  • 18,427
  • 4
  • 26
  • 52
3
>>> df.assign(names=[[firstname, fullname[len(firstname):]] 
                     for fullname, firstname in df[['FullName', 'FirstName']].values])
        FullName FirstName              names
0  MichaelJordan   Michael  [Michael, Jordan]
1     KobeBryant      Kobe     [Kobe, Bryant]
2    LeBronJames    LeBron    [LeBron, James]
Alexander
  • 87,529
  • 23
  • 162
  • 169
0

This is oneliner with an apply. Split the FullName on the length of the FirstName:

df['Names'] = df.apply(lambda row: [row['FullName'][:len(row['FirstName'])], row['FullName'][len(row['FirstName']):]] if row['FullName'].startswith(row['FirstName']) else '', axis=1)
        FullName FirstName              Names
0  MichaelJordan   Michael  [Michael, Jordan]
1     KobeBryant      Kobe     [Kobe, Bryant]
2    LeBronJames    LeBron    [LeBron, James]


Dave
  • 1,277
  • 7
  • 21