Anonymize database data implementing k-anonymity. Generalize attributes like converting exact age to age ranges and suppress identifiers so every record is indistinguishable from at least k-1 other records.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
I'm outlining the k-anonymity concept with a generic Python example that generalizes ages into ranges and masks identifiers using synthetic data to demonstrate data anonymization while ensuring group sizes meet k. I'll include disclaimers about the example's educational purpose and data privacy best practices.
One common way to achieve k‑anonymity is to pick a set of quasi‑identifier columns (e.g. age, ZIP code, gender) and then generalize or suppress those columns until every combination appears in at least (k) records. Direct identifiers (names, SSNs, etc.) are dropped entirely.
Here's a simple example in Python using pandas that illustrates the idea of generalizing ages into ranges and truncating ZIP codes to the first 3 digits until each group has size ≥ k:
python
import pandas as pd
import numpy as np
def generalize_age(age):
# Convert exact age to decade ranges: 20–29, 30–39, etc.
lower = (age // 10) * 10
upper = lower + 9
return f"{lower}-{upper}"
def generalize_zip(zip_code, prefix_len=3):
# Keep only the first prefix_len characters of the ZIP/postcode
return str(zip_code)[:prefix_len] if pd.notna(zip_code) else np.nan
def kanonymize(df, quasi_ids, k):
# Drop direct identifiers
df = df.drop(columns=['name', 'ssn'], errors='ignore')
# Apply simple generalizations
if 'age' in df.columns:
df['age'] = df['age'].apply(generalize_age)
if 'zip' in df.columns:
df['zip'] = df['zip'].apply(lambda z: generalize_zip(z, 3))
# Check group sizes; if any group is too small, generalize further
while True:
group_sizes = df.groupby(quasi_ids).size()
small_groups = group_sizes[group_sizes < k]
if small_groups.empty:
break # all groups satisfy k-anonymity
# Example strategy: further generalize ZIP prefixes
if 'zip' in quasi_ids:
current_prefix_len = len(df['zip'].iloc[0])
new_prefix_len = max(0, current_prefix_len - 1)
df['zip'] = df['zip'].apply(lambda z: generalize_zip(z, new_prefix_len))
else:
# If no more generalization possible, suppress rows
df = df[~df[quasi_ids].apply(tuple, axis=1).isin(small_groups.index)]
return df
# Example usage with mock data
data = {
'name': ['Alice', 'Bob', 'Carol', 'Dave'],
'age': [27, 29, 34, 36],
'zip': ['12345', '12346', '67890', '67891'],
'diagnosis': ['A', 'A', 'B', 'B']
}
df = pd.DataFrame(data)
anon_df = kanonymize(df, quasi_ids=['age', 'zip', 'diagnosis'], k=2)
print(anon_df)
In this toy dataset, we drop the name, convert ages to decade ranges, and truncate ZIP codes. The kanonymize function then checks group sizes and, if necessary, further generalizes ZIP codes or suppresses rows to ensure each quasi‑identifier combination appears at least twice (k=2).
In a production setting you would:
Define appropriate generalization hierarchies for each quasi‑identifier (e.g. age → decade → broad age bands; ZIP → 5‑digit → 3‑digit → state).
Choose a strategy for resolving small groups (e.g. further generalization vs. suppression).
Validate that the transformed dataset meets your chosen value of (k) without overly degrading utility.