Below are a couple of common approaches to anonymise a pandas DataFrame column of first names by replacing them with another string.
1. Replace All Names With the Same String
If you simply want to replace every first name with a fixed string (e.g., "Anonymised"), you can do this in one line:
import pandas as pd
# Example DataFrame
data = {'first_name': ['Alice', 'Bob', 'Charlie', 'Alice']}
df = pd.DataFrame(data)
# Replace every first name with the same string
df['first_name'] = "Anonymised"
print(df)
Output:
first_name
0 Anonymised
1 Anonymised
2 Anonymised
3 Anonymised
2. Replace Each Name With a Unique Pseudonym
If you need to maintain a one-to-one mapping from the original name to a new pseudonym (for example, to later re-identify records if needed or just to ensure that records with the same first name get the same pseudonym), you can build a mapping. One approach is to assign a unique identifier to each unique name:
import pandas as pd
# Example DataFrame
data = {'first_name': ['Alice', 'Bob', 'Charlie', 'Alice']}
df = pd.DataFrame(data)
# Create a mapping from the original name to a pseudonym
unique_names = df['first_name'].unique()
mapping = {name: f'User_{i+1}' for i, name in enumerate(unique_names)}
# Anonymise the first_name column using the mapping
df['first_name'] = df['first_name'].map(mapping)
print(df)
Output (mapping may vary):
first_name
0 User_1
1 User_2
2 User_3
3 User_1
3. Anonymise Using a Hash Function
Another method is to hash each name (using, for example, SHA-256) so that the output is non-reversible. This method is useful when you want to hide the original values but still have a consistent pseudonym for each name:
import pandas as pd
import hashlib
# Example DataFrame
data = {'first_name': ['Alice', 'Bob', 'Charlie', 'Alice']}
df = pd.DataFrame(data)
def anonymise_name(name):
# Hash the name using SHA-256 and take the first 10 characters of the hexadecimal digest.
return hashlib.sha256(name.encode()).hexdigest()[:10]
df['first_name'] = df['first_name'].apply(anonymise_name)
print(df)
Output (hashed values may vary):
first_name
0 3bc5106292
1 cd13b10a49
2 3f79bb7b5e
3 3bc5106292
Summary
- Simple replacement: Use a constant string for all rows if you do not need to differentiate between individuals.
- Mapping replacement: Use a dictionary mapping to provide each unique name with a unique pseudonym.
- Hashing: Use a cryptographic hash to anonymise the names in a consistent, non-reversible way.
Choose the approach that fits your requirements.