Python 将df中的一列拆分为另一列值

Python 将df中的一列拆分为另一列值,python,pandas,Python,Pandas,在python中,我有以下df(第一行中的标题): 我正试图根据“FirstName”中的值在“FullName”中分割每条记录,但运气不好 这就是我所尝试的: df['Names'] = df['FullName'].str.split(df['FirstName']) 这会产生错误: 'Series' objects are mutable, thus they cannot be hashed 期望输出: print(df['Names']) ['Michael', 'Jordan'

在python中,我有以下df(第一行中的标题):

我正试图根据“FirstName”中的值在“FullName”中分割每条记录,但运气不好

这就是我所尝试的:

df['Names'] = df['FullName'].str.split(df['FirstName'])
这会产生错误:

'Series' objects are mutable, thus they cannot be hashed
期望输出:

print(df['Names'])

['Michael', 'Jordan']
['Kobe', 'Bryant']
['LeBron', 'James']
str.replace

同样的想法,但使用
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

由于您正在进行行操作,因此我们可以使用apply

其思想是将名字替换为self+逗号分隔

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

这是一个应用程序的一行。根据
名字的长度拆分
全名

df['Names']=df.apply(lambda行:[row['FullName'][:len(row['FirstName']),row['FullName']][len(row['FirstName']):]]如果行['FullName'],则应用。开始使用(row['FirstName'])else'',axis=1)

你能发布你想要的样本输出吗?这正是我想要的。非常感谢。聪明的。。。鉴于名字通常是。。。UH第一个(-):
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
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
        FullName FirstName              Names
0  MichaelJordan   Michael  [Michael, Jordan]
1     KobeBryant      Kobe     [Kobe, Bryant]
2    LeBronJames    LeBron    [LeBron, James]


>>> 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]