【问题标题】:How to replace part of email address with another string in pandas?如何用熊猫中的另一个字符串替换部分电子邮件地址?
【发布时间】:2018-02-24 18:54:45
【问题描述】:

我有一个包含电子邮件地址的数据框。我需要用“.mn”替换电子邮件地址的每个结尾。我所说的结尾是“.org”、“.com”等。

Ex. John@smith.com becomes John@smith.mn

不知道我做错了什么。

这是我目前所拥有的,但这并没有取代或给我一条错误消息:

email['ADDR'] = email['ADDR'].str.replace(r'[.]{2,}', '.mn')

提前谢谢你。

【问题讨论】:

    标签: python string pandas dataframe replace


    【解决方案1】:

    应该这样做:

    email['ADDR'] = email['ADDR'].str.replace('.{3}$', 'mn')
    

    如果需要处理可变长度域(.edu.com1 等),可以使用:

    email
    
                 ADDR
    0  john@smith.com
    1    test@abc.edu
    2    foo@bar.abcd
    
    email['ADDR'].str.replace('\..{2,}$', '.mn')
    
    0    john@smith.mn
    1      test@abc.mn
    2       foo@bar.mn
    Name: ADDR, dtype: object
    

    【讨论】:

    • 只要打开问题,就有你漂亮简洁的答案~
    【解决方案2】:

    另一种处理可变长度顶级结尾的方法是使用str.rsplit

    In[72]:
    df = pd.DataFrame({'email':['John@smith.com','John@smith.x','John@smith.hello']})
    df
    
    Out[72]: 
                  email
    0    John@smith.com
    1      John@smith.x
    2  John@smith.hello
    
    In[73]:
    df['email'] = df['email'].str.rsplit('.').str[0] +'.mn'
    df
    
    Out[73]: 
               email
    0  John@smith.mn
    1  John@smith.mn
    2  John@smith.mn
    

    这将找到最后一个尾随点,取左侧并附加新的所需后缀

    【讨论】:

    • 啊,很好很简单。
    猜你喜欢
    • 1970-01-01
    • 2020-01-27
    • 1970-01-01
    • 2019-09-26
    • 1970-01-01
    • 2011-06-13
    • 2015-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多