To anonymize a pandas column containing first names, you can replace each unique name with a consistent placeholder string. This ensures that the same name always maps to the same anonymized value, preserving the structure of the data while protecting identity.
✅ Approach Overview
- Identify Unique Names: Extract the unique names from the column.
- Create Mapping: Assign each unique name a unique placeholder string (e.g.,
Name_1, Name_2, etc.).
- Apply Mapping: Use the
.map() function to replace the original names with their corresponding placeholder strings.
This method is efficient and deterministic, meaning the same input will always produce the same anonymized output.
🧩 Example Code
import pandas as pd
# Sample DataFrame
df = pd.DataFrame({'FirstNames': ['Alice', 'Bob', 'Alice', 'Charlie', 'Bob']})
# Step 1: Get unique names
unique_names = df['FirstNames'].unique()
# Step 2: Create a mapping dictionary
name_mapping = {name: f'Name_{i}' for i, name in enumerate(unique_names, start=1)}
# Step 3: Apply the mapping to the column
df['FirstNames'] = df['FirstNames'].map(name_mapping)
# Output the anonymized DataFrame
print(df)
📊 Output
FirstNames
0 Name_1
1 Name_2
2 Name_1
3 Name_3
4 Name_2
🔍 Notes
- Consistency: Each unique name is consistently replaced with the same placeholder.
- Scalability: This approach works well even with large datasets.
- Customization: You can customize the placeholder pattern (e.g.,
'User_1', 'Anon_001') by modifying the string in the dictionary comprehension.
- Case Sensitivity: If needed, normalize the names (e.g., lowercase) before mapping to avoid treating similar names differently due to case.
🛡️ Optional: Case Normalization
If the names may vary in case (e.g., 'Alice' vs 'alice'), you can normalize them before mapping:
df['FirstNames'] = df['FirstNames'].str.lower()
This ensures that 'Alice' and 'alice' are treated as the same name and receive the same placeholder.
This method provides a simple yet effective way to anonymize personal data in pandas while maintaining data integrity.