MAGNUSContact
← All posts
Practical Application

Hands-On: Pseudonymize a Member File in Python Before You Share It or Paste It Into an AI Tool

Sophia JungNovember 25, 2026

Listen: Hands-On: Pseudonymize a Member File in Python Before You Share It or Paste It Into an AI Tool

0:00 / 0:00

Part of the Hands-On AI for Data Pros series.

Yesterday's post explained why pseudonymization matters. This one builds it. By the end you will have a short Python script that takes a member extract and produces a working copy you can hand to an analyst, a vendor, or an approved AI tool with much less risk.

Before you start

  • Run it on the synthetic file below first. Nothing here uses real member data.
  • You need Python 3 and pandas. Plan on an hour.
  • Pseudonymization is one layer. It does not replace your access controls, your vendor reviews, or your governance committee's sign-off.

What the script does

Each column and its treatment: direct identifiers dropped, member ID becomes a keyed token, birth date becomes an age band, ZIP becomes ZIP3, join date is shifted, small groups are generalized.

  • Drops name, email, phone, and the last four of a Social Security number. They are removed, not hashed.
  • Replaces the member ID with a keyed token. The token comes from HMAC-SHA256 with a secret key only you hold. Without the key, nobody can recompute it by trying every possible member number, which is how the New York taxi data was undone.
  • Generalizes date of birth to an age band and ZIP to its first three digits.
  • Shifts dates by a fixed number of days, up to 30 either way, different for each member. Time between a member's own dates stays the same.
  • Checks group sizes. It looks at the combination of age band, ZIP3, and branch. Where a combination has fewer than five members, it generalizes step by step, first the branch, then the ZIP3, then the age band, until every group has at least five.

Step 1: make the practice file

make_members.py builds members.csv and accounts.csv with about 500 invented members, using names from a short made-up list and addresses that do not exist. It also plants a few rare combinations so the group-size check has something to catch. Download it here: make_members.py.

python make_members.py

Step 2: set the key

The key lives in an environment variable, not in the script and not in the folder with the data. Generate a long random value and store it in your password manager or secrets vault.

export PSEUDO_KEY="paste-a-long-random-secret-here"

The script refuses to run if the key is missing or shorter than 16 characters.

Step 3: run the script

"""Pseudonymize a member extract before sharing it or using it in an analysis or AI tool.
Reads members.csv (synthetic or approved data only). Writes members_pseudonymized.csv.
The secret key comes from the environment, never from the code or the file."""
import os, sys, hmac, hashlib, datetime as dt
import pandas as pd

KEY = os.environ.get("PSEUDO_KEY", "").encode()
if len(KEY) < 16:
    sys.exit("Set PSEUDO_KEY to a long random secret (16+ characters) kept outside this folder.")
AS_OF = dt.date(2026, 11, 1)   # reference date for ages
K = 5                          # smallest group size allowed for the quasi-identifiers

def token(value, purpose="id"):
    """Keyed hash: same input and key give the same token. Without the key it cannot be recomputed."""
    return hmac.new(KEY, f"{purpose}|{value}".encode(), hashlib.sha256).hexdigest()

df = pd.read_csv("members.csv", dtype=str).drop_duplicates("member_id")
out = pd.DataFrame()
out["member_token"] = "M-" + df["member_id"].map(lambda v: token(v)[:16])

# Direct identifiers (name, email, phone, ssn_last4) are dropped, not hashed.
# Quasi-identifiers are generalized: age band instead of birth date, ZIP3 instead of ZIP.
age = df["dob"].map(lambda d: (AS_OF - dt.date.fromisoformat(d)).days // 365)
out["age_band"] = (age // 10 * 10).astype(str) + "s"
out["zip3"] = df["zip"].str[:3]
out["branch"] = df["branch"]

# Date shifting: each member gets a fixed offset of -30..+30 days, so intervals within a member survive.
def shifted(row):
    off = int(token(row["member_id"], "shift")[:8], 16) % 61 - 30
    return (dt.date.fromisoformat(row["join_date"]) + dt.timedelta(days=off)).isoformat()
out["join_date_shifted"] = df.apply(shifted, axis=1)

# k-anonymity check on the quasi-identifiers. Small groups are generalized step by step:
# first drop the branch, then the ZIP3, then the age band, until every group has at least K members.
qi = ["age_band", "zip3", "branch"]
def group_sizes():
    return out.groupby(qi)["member_token"].transform("size")
print(f"Rows in groups smaller than {K} before generalizing: {int((group_sizes() < K).sum())}")
for col in ["branch", "zip3", "age_band"]:
    small = group_sizes() < K
    if not small.any():
        break
    out.loc[small, col] = "*"
smallest = int(group_sizes().min())
print(f"Smallest group after generalizing: {smallest}")
if smallest < K:
    print("WARNING: some groups are still smaller than K. Do not release this file as is.")

out.to_csv("members_pseudonymized.csv", index=False)
print(f"{len(out)} rows written to members_pseudonymized.csv")

Download the full script: pseudonymize.py.

On the practice file, we ran it and got this: 59 rows were in groups smaller than 5 before generalizing, and the smallest group afterward was exactly 5. The output has 501 rows (a duplicate member ID in the practice file was dropped) and five columns: member_token, age_band, zip3, branch, and join_date_shifted.

Step 4: check your own work

Do not take the script's word for it. Run these checks every time.

  • No identifiers left. Open the output and confirm no name, email, phone, or full birth date appears. Search for an @ sign as a quick test.
  • Tokens are unique. In our test, 501 rows produced 501 distinct tokens.
  • A different key gives different tokens. We reran with another key, and none of the tokens matched. That is what you want. It means the tokens depend on the secret.
  • Smallest group is at least K. The script prints this number. If it prints a warning, do not release the file.
  • Join your results back. If you use the same key and a different table, such as accounts, you can create the same tokens and link the tables. Do that only for projects that need linking.

Step 5: a controlled lookup

Sometimes a finding needs a human follow-up, such as an account that looks like fraud. For that you need to go from a token back to a member. This script recomputes tokens for your member list and finds the match, which only works with the key. Treat each use as an event to log.

"""Authorized lookup: given a token, find the member id by recomputing tokens for a candidate list.
Only someone holding PSEUDO_KEY can do this. Log every use."""
import os, sys, hmac, hashlib, pandas as pd
KEY = os.environ["PSEUDO_KEY"].encode()
def token(value, purpose="id"):
    return hmac.new(KEY, f"{purpose}|{value}".encode(), hashlib.sha256).hexdigest()
wanted = sys.argv[1]
ids = pd.read_csv("members.csv", dtype=str)["member_id"].drop_duplicates()
hit = [i for i in ids if "M-" + token(i)[:16] == wanted]
print(hit[0] if hit else "no match")

Download the full script: reidentify_lookup.py.

On the practice file, the token in the second data row of the output resolved to member 100002, which matched the source row.

Where this can go wrong

  • Free text. If your extract has note fields, the script does not touch them. Drop them or clean them first.
  • Rare combinations you did not list. The group-size check covers the three columns it names. If you add occupation, or a city, add it to the list.
  • A key in the wrong place. If the key is saved in a notebook or emailed around, the protection is gone.
  • Balances and dates. Unusual balances can identify a member to someone who knows them. Consider rounding or banding amounts for external sharing.
  • Too much trust. A pseudonymized file is still member data. Keep it inside your approved systems unless your governance process says otherwise.

A good rule for AI tools

If the task does not need identity, the tool gets the pseudonymized file, or only column names and a handful of invented rows. If the task needs identity, do it inside an approved system and ask your compliance team first.

The takeaway

It is under 60 lines of code, and the hard part is not the code. It is deciding who holds the key, who can look up a member, and which projects get the pseudonymized copy by default. Write those decisions down.

Sources

About the author

Sophia Jung is the founder of Magnus. She attended Johns Hopkins for Data Science and Cloud Computing, with a background spanning full-stack engineering at Ford Motor Company and business intelligence leadership at a credit union, where she built a BI department from scratch. Magnus combines that technical depth with direct credit union experience.

More about our founder →