如何在Python中的特定列中屏蔽特定值?

时间:2019-07-12 02:34:59

标签: python pandas

我有一个.csv文件,具有5列和大约5000行。 .csv文件中名为“摘要”的特定列中,有信用卡号和一些文本。看起来像这样

  

嘿,这项工作需要尽快完成,并用卡号签证5611000043310001支付

我想阅读此列,取出数字(也许使用正则表达式),然后对后4位数字进行掩码,并使用.csv文件中的掩码数字按原样写出整行。

  

嘿,这项工作需要尽快完成,并用卡号Visa 561100004331 ****支付

我该怎么办?

2 个答案:

答案 0 :(得分:1)

使用正则表达式,您可以执行以下操作:

import re

>> s = "hey this job needs to be done asap and pay with card# visa 5611000043310001"
>> re.sub(r"(\d{12})\d{4}",r"\1****",s)

'hey this job needs to be done asap and pay with card# visa 561100004331****'

因此,(\d{12})基本上与前12位数字匹配(括号内没有替换前12位的数字)。然后是4位数,我们用星号代替。 \1是第一个组的占位符,被替换省略,因此这里指的是前12位数字。

答案 1 :(得分:0)

下面带有regex的替换功能查找正好16位数字,并屏蔽后4位数字。

所以这段代码:

import docx 
import csv

doc = docx.Document()

with open('csv.csv', newline='') as f:
    csv_reader = csv.reader(f) 
    csv_headers = next(csv_reader)
    csv_cols = len(csv_headers)

    table = doc.add_table(rows=2, cols=csv_cols)
    hdr_cells = table.rows[0].cells

    for i in range(csv_cols):
        hdr_cells[i].text = csv_headers[i]

    for row in csv_reader:
        row_cells = table.add_row().cells
        for i in range(csv_cols):
            row_cells[i].text = row[i]

doc.add_page_break()
doc.save("data.docx")

应打印以下内容: eg_summaries = [ 'blah blah card# visa 5611000043310001', 'blah blah card# visa 5611000043310001 with text after', '5611000043310001', 'visa: 5611000043310001 and random number > 16 digits: 0011237324763246723487243', ] df = pd.DataFrame({'summary': eg_summaries }) df['summary'].replace(r'\b(\d{12})\d{4}\b', r'\1****', inplace=True, regex=True) print (df.summary)

相关问题