首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在python中,在dataframe中清除重复的首名和姓氏值。

在python中,在dataframe中清除重复的首名和姓氏值。
EN

Stack Overflow用户
提问于 2022-07-21 18:34:11
回答 1查看 58关注 0票数 1

我试图删除一个单元格中的重复单词,以清理处理姓名(丈夫和妻子)的数据。

代码语言:javascript
复制
          Current                  Desired
0  John Doe and Jane Doe         John Doe and Jane doe
1  John Doe and John Doe         John Doe
2  John Doe                      John Doe
3  Jane Doe and Jane Doe         Jane Doe
4  Jane Doe and Jane             Jane Doe
5  John and John Doe             John Doe

我有以下内容,可以很好地将John and John清除为John

代码语言:javascript
复制
df['out'] = df.Current.str.split(' and ').map(lambda x : ' and '.join(set(x)))

我如何调整我的代码,以考虑到其他情况,以清理名字和姓氏?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-21 18:56:02

尝试:

代码语言:javascript
复制
import re

pat = re.compile(r"(.+?)\s+and\s+(.+)")


def clean(x):
    m = pat.match(x)

    if not m:
        return x

    if m.group(1).split()[0] == m.group(2).split()[0]:
        return max(m.group(1), m.group(2), key=len)

    return x


df["Desired 2"] = df["Current"].apply(clean)
print(df)

指纹:

代码语言:javascript
复制
                 Current                Desired              Desired 2
0  John Doe and Jane Doe  John Doe and Jane doe  John Doe and Jane Doe
1  John Doe and John Doe               John Doe               John Doe
2               John Doe               John Doe               John Doe
3  Jane Doe and Jane Doe               Jane Doe               Jane Doe
4      Jane Doe and Jane               Jane Doe               Jane Doe
5      John and John Doe               John Doe               John Doe
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73071114

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档