0

All columns (NAME,MARKS,CONTACT,MAILID,SSN) except NO column should be replaced with * (stars). How can I achieve using python replace function.

Input:
NO,NAME,MARKS,CONTACT,MAILID,SSN
1,HENRY,89,9659651122,[email protected],123-456-789
2,JOHN,88,8885566000,[email protected],234-456-789
3,JACK,76,9988770099,[email protected],345-678-901
4,MARY,85,4455889933,[email protected],456-789-012
5,CLNT,77,5599886699,[email protected],567-890-123

Output:
NO,NAME,MARKS,CONTACT,MAILID,SSN
1,*****,**,**********,*****_**@***.***,***-***-***
2,****,**,**********,****_**@***.***,***-***-***
3,****,**,**********,******@***.***,***-***-***
4,****,**,**********,******@***.***,***-***-***
5,****,**,**********,****_**@***.***,***-***-***

When I try below line of code, it is working only for Alphanumeric column values, when I include integer columns (MARKS,CONTACT) it is failing with the mentioned error message. How can i replace all required columns with a * (star) using one loop if possible.

Code:

df = pd.read_csv("input.csv")
for col in ['NAME','MARKS','CONTACT','MAILID','SSN']:
    df[col] = df[col].str.replace('[a-zA-Z0-9]','*')

Error: raise AttributeError("Can only use .str accessor with string values!") AttributeError: Can only use .str accessor with string values!

1 Answer 1

1

Use dtype=object as parameter of read_csv:

cols = ['NAME', 'MARKS', 'CONTACT', 'MAILID', 'SSN']
df = pd.read_csv('input.csv', dtype=object)
df[cols] = df[cols].replace(r'[a-zA-Z0-9]', '*', regex=True)
df.to_csv('output.csv', index=False)

Output:

NO,NAME,MARKS,CONTACT,MAILID,SSN
1,*****,**,**********,*****_**@***.***,***-***-***
2,****,**,**********,****_**@***.***,***-***-***
3,****,**,**********,******@***.***,***-***-***
4,****,**,**********,******@***.***,***-***-***
5,****,**,**********,****_**@***.***,***-***-***
Sign up to request clarification or add additional context in comments.

1 Comment

Does it solve your problem?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.