【问题标题】:python - Replace first five characters in a column with asteriskspython - 用星号替换列中的前五个字符
【发布时间】:2019-07-02 21:34:28
【问题描述】:

我在 CSV 文件中有一个名为 SSN 的列,其值如下

289-31-9165

我需要遍历此列中的值并替换前五个字符,使其看起来像这样

***-**-9165

这是我目前的代码:

emp_file = "Resources/employee_data1.csv"

emp_pd = pd.read_csv(emp_file) 

new_ssn = emp_pd["SSN"].str.replace([:5], "*")

emp_pd["SSN"] = new_ssn

如何循环遍历该值并仅用星号替换前五个数字(仅)并保持 hiphens 不变?

【问题讨论】:

    标签: python pandas replace


    【解决方案1】:

    与 Mr. Me 类似,这将删除前 6 个字符之前的所有内容,并用您的新格式替换它们。

    emp_pd["SSN"] = emp_pd["SSN"].apply(lambda x: "***-**" + x[6:])
    

    【讨论】:

    • @KrithikaRaghavendran,虽然这是一个好方法,但 pandas replace() 是实现这一目标的更快方法,您不需要调用 lambda,但是除了接受它之外,您还可以投票赞成答案:-) + 1 来自我。
    【解决方案2】:

    您可以使用 replace() 方法简单地实现这一点:

    示例数据框:

    借用@AkshayNevrekar..

    >>> df
               ssn
    0  111-22-3333
    1  121-22-1123
    2  345-87-3425
    

    结果:

    >>> df.replace(r'^\d{3}-\d{2}', "***-**", regex=True)
               ssn
    0  ***-**-3333
    1  ***-**-1123
    2  ***-**-3425
    

    >>> df.ssn.replace(r'^\d{3}-\d{2}', "***-**", regex=True)
    0    ***-**-3333
    1    ***-**-1123
    2    ***-**-3425
    Name: ssn, dtype: object
    

    或者:

    df['ssn'] = df['ssn'].str.replace(r'^\d{3}-\d{2}', "***-**", regex=True)
    

    【讨论】:

      【解决方案3】:

      把你的星号放在前面,然后抓住最后 4 位数字。

      new_ssn = '***-**-' + emp_pd["SSN"][-4:]
      

      【讨论】:

      • 最后 4 个应该是:new_ssn = '***-**-' + emp_pd["SSN"][-4:]
      【解决方案4】:

      您可以使用regex

      df = pd.DataFrame({'ssn':['111-22-3333','121-22-1123','345-87-3425']})
      
      def func(x):
          return re.sub(r'\d{3}-\d{2}','***-**', x)
      
      df['ssn'] = df['ssn'].apply(func)    
      
      print(df)
      

      输出:

                 ssn                                                                                                                                 
      0  ***-**-3333                                                                                                                                 
      1  ***-**-1123                                                                                                                                 
      2  ***-**-3425  
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-07-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多