代码之家  ›  专栏  ›  技术社区  ›  anky

仅在系列中使用参数替换s.str.startwith

  •  -1
  • anky  · 技术社区  · 7 年前

    我有一个 df 我要在其上筛选列并替换 str.startswith

    df = pd.DataFrame(data={'fname':['Anky','Anky','Tom','Harry','Harry','Harry'],'lname':['sur1','sur1','sur2','sur3','sur3','sur3'],'role':['','abc','def','ghi','','ijk'],'mobile':['08511663451212','','0851166346','','0851166347',''],'Pmobile':['085116634512','1234567890','8885116634','','+353051166347','0987654321'],'Isactive':['Active','','','','Active','']})
    

    通过执行以下行:

    df['Pmobile'][df['Pmobile'].str.startswith(('08','8','+353'),na=False)]
    

    0      085116634512
    2      8885116634
    4      +353051166347
    

    s.str.startswith() 例如: ('08','8','+3538') 除了元组中的起始数字外,不要触摸任何其他数字(在飞行中)?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Sach    7 年前

    您可以使用pandas替换为regex。

    下面是示例代码。

    df.Pmobile.replace(regex={r'^08':'',r'^8':'',r'^[+]353':''})
    

    https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html

        2
  •  1
  •   Loochie    7 年前

    df.Pmobile = df.Pmobile.replace(r'^[08|88|+3538]', '')