gpt4 book ai didi

python - 用另一个列值拆分 df 中的列

转载 作者:行者123 更新时间:2023-12-01 15:17:49 24 4
gpt4 key购买 nike

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

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

我正在尝试根据“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

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

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

关于python - 用另一个列值拆分 df 中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60345858/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com