本文介绍了python - 用星号替换列中的前五个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 CSV 文件中有一个名为 SSN 的列,其值如下
I have a column called SSN in a CSV file with values like this
289-31-9165
我需要遍历此列中的值并替换前五个字符,使其看起来像这样
I need to loop through the values in this column and replace the first five characters so it looks like this
***-**-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
如何遍历值并仅用星号替换前五个数字(仅)并保持 hihens 不变?
How do I loop through the value and replace just the first five numbers (only) with asterisks and keep the hiphens as is?
推荐答案
与 Mr. Me 类似,这将删除前 6 个字符之前的所有内容,并将它们替换为您的新格式.
Similar to Mr. Me, this will instead remove everything before the first 6 characters and replace them with your new format.
emp_pd["SSN"] = emp_pd["SSN"].apply(lambda x: "***-**" + x[6:])
这篇关于python - 用星号替换列中的前五个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!