首页 > 解决方案 > 从其他系列对象修改系列

问题描述

所以我有这样的数据:

Id  Title                   Fname   lname   email
1   meeting with Jay, Aj    Jay     kay     jk@something.com
1   meeting with Jay, Aj    Aj      xyz     aj@something.com
2   call with Steve         Steve   Jack    st@something.com
2   call with Steve         Harvey  Ray     h@something.com
3   lunch Mike              Mil     Mike    m@something.com

我想从标题中删除每个唯一 ID 的名字和姓氏。我尝试按 Id 分组,它为 Title、Fname、Lname 等提供系列对象

df.groupby('Id')

我已将 Fname 与.agg(lambda x: x.sum() if x.dtype == 'float64' else ','.join(x))

& 保存在concated数据框中。

同样,所有其他列都会被聚合。问题是如何根据这个聚合系列替换 Title 中的值。

concated['newTitle']  = [ concated.Title.str.replace(e[0]).replace(e[1]).replace(e[1])
                     for e in
                     zip(concated.FName.str.split(','), concated.LName.str.split(','))
                     ]

我想要这样的东西,或者其他方式,对于每个 Id,我可以获得带有替换值的 newTitle。

输出如下:

Id Title
1  Meeting with ,
2  call with 
3  lunch 

标签: pythonpandas

解决方案


通过加入 Fname 和 lname 并替换来创建映射器系列,

s = df.groupby('Id')[['Fname', 'lname']].apply(lambda x: '|'.join(x.stack()))
df.set_index('Id')['Title'].replace(s, '', regex = True).drop_duplicates()


Id
1    meeting with , 
2         call with 
3             lunch 

推荐阅读