# How to predict gender from names in Python

Plain-Markdown twin of <https://gender-api.com/en/gender-from-name-python>.
Last reviewed 2026-12-05. Every snippet was run against the API before publishing.

One request per row works for ten names and falls over at a hundred thousand. This is the
version for a real pandas DataFrame: deduplicated, batched, retried where a retry helps,
and with a probability and a record count on every row.

## The short answer

- POST the names to `/v2/gender` as a JSON array — up to **100 per request**, each with an
  `id` to join the answer back. Answers come back in request order, each with your `id`
  inside `input`.
- Deduplicate on **name and country** first. You pay one credit per distinct name found;
  names that are not found (`result_found: false`) cost nothing.
- Retry timeouts and 5xx with a back-off. Do not retry a 400 (bad request, more than 100
  entries, invalid token) or a 401 `limit-exceeded` (not enough credits for the batch).
- Keep `probability` (0–1) and `samples` as columns and set a cut-off on both.

## An offline package or an API?

The usual offline choice is the `gender-guesser` package on PyPI: a fixed dictionary that
returns one of six labels (`male`, `female`, `mostly_male`, `mostly_female`, `andy`,
`unknown`) and can prefer a country such as `great_britain`. If your names are common and a
label is all you need, that may be enough. Use an API when you need a probability and a
record count to set a cut-off on, an answer for the person's country, or names outside a
fixed list.

## One name

```python
import requests

response = requests.post(
    "https://gender-api.com/v2/gender",
    headers={"Authorization": "Bearer YOUR_TOKEN"},
    json={"first_name": "Andrea", "country": "IT"},
    timeout=30,
)
print(response.json())
```

```json
{
    "input": {"first_name": "Andrea", "country": "IT"},
    "details": {"credits_used": 1, "samples": 1068, "country": "IT",
                "first_name_sanitized": "andrea", "duration": "12ms"},
    "result_found": true,
    "first_name": "Andrea",
    "probability": 0.95,
    "gender": "male"
}
```

## A whole DataFrame

```python
import time

import pandas as pd
import requests

API_URL = "https://gender-api.com/v2/gender"
BATCH_SIZE = 100  # the most names one request accepts

session = requests.Session()
session.headers["Authorization"] = "Bearer YOUR_TOKEN"


def post_batch(rows, attempts=5):
    """Send up to 100 lookups. Retry only what a retry can fix."""
    for attempt in range(attempts):
        try:
            response = session.post(API_URL, json=rows, timeout=30)
        except (requests.ConnectionError, requests.Timeout):
            response = None

        if response is not None and response.status_code < 500:
            # 400 = something in the request is wrong, 401 = no credits left.
            # Neither gets better by asking again, so stop here.
            response.raise_for_status()
            return response.json()

        if attempt < attempts - 1:
            time.sleep(2 ** attempt)  # 1, 2, 4, 8 seconds

    raise RuntimeError("Gender API not reachable after retries")


def add_gender(df, name_col="first_name", country_col=None):
    keys = [name_col] + ([country_col] if country_col else [])

    # One lookup per distinct name (and country), not per row.
    unique = df[keys].copy()
    unique[name_col] = unique[name_col].astype("string").str.strip()
    valid = unique[name_col].str.len().between(1, 50).fillna(False)
    unique = unique[valid].drop_duplicates().reset_index(drop=True)

    lookups = []
    for i, row in unique.iterrows():
        item = {"first_name": row[name_col], "id": f"row-{i}"}
        if country_col and pd.notna(row[country_col]):
            item["country"] = row[country_col]
        lookups.append(item)

    found = {}
    for start in range(0, len(lookups), BATCH_SIZE):
        for result in post_batch(lookups[start:start + BATCH_SIZE]):
            if result.get("result_found"):
                found[int(result["input"]["id"].removeprefix("row-"))] = {
                    "gender": result["gender"],
                    "probability": result["probability"],
                    "samples": result["details"]["samples"],
                }

    columns = ["gender", "probability", "samples"]  # also when nothing was found
    lookup = unique.join(pd.DataFrame.from_dict(found, orient="index", columns=columns))
    lookup = lookup.rename(columns={name_col: "_key"})

    out = df.copy()
    out["_key"] = out[name_col].astype("string").str.strip()
    return out.merge(lookup, on=["_key"] + keys[1:], how="left").drop(columns="_key")


customers = pd.read_csv("customers.csv")
customers = add_gender(customers, name_col="first_name", country_col="country")

# Starting points, not recommendations - measure your own.
customers["confident"] = (customers["probability"] >= 0.9) & (customers["samples"] >= 20)
```

Output of a test run with a duplicate, a leading space, an empty cell, a blank string, an
unknown name and a name over the 50-character limit (150 rows, so the batch crossed a
100-name boundary):

```
  first_name country  gender  probability  samples  confident
0     Andrea      IT    male         0.95   1068.0       True
1     Andrea      DE  female         1.00    871.0       True
2        Kim     NaN  female         0.68  48002.0      False
3        Jan      NL    male         0.99     92.0       True
4        NaN      DE     NaN          NaN      NaN      False
5                 DE     NaN          NaN      NaN      False
6    Xqzzvbt     NaN     NaN          NaN      NaN      False
7   aaaa…aaa     NaN     NaN          NaN      NaN      False
8     Andrea      IT    male         0.95   1068.0       True
```

## Errors, retries and credits

| What comes back | What it means | What the code does |
|---|---|---|
| 200, one entry has a `status` field | That one name was invalid; the rest of the batch answered | Leaves that row empty |
| 400 for the whole request | More than 100 entries, a missing or invalid token | Raises — fix the call |
| 401 `limit-exceeded` | Not enough credits left for every name in the batch | Raises — top up, then rerun |
| Timeout or 5xx | The request did not get through | Waits 1, 2, 4, 8 s and retries |

A batch needs enough credits for every name in it before it runs, but is only charged for
the names it finds. Credits are bought in advance and are valid for 12 months from the
last purchase.

## Which answers to trust

A probability alone cannot tell a 0.95 resting on five records from a 0.95 resting on a
thousand; the sample count can. Two cut-offs give three groups: confident and well-backed
(use it), confident but thin (review it), below the probability cut-off (the name is
genuinely mixed — use a neutral salutation; more records will not make Kim less
ambiguous). Do not copy 0.9 and 20 — measure your own on hand-labelled rows, as described
in [How to infer gender from a name](https://gender-api.com/infer-gender-from-names.md).

## Beyond first names

- Full name only: send `full_name` to `/v2/gender/by-full-name` (one credit, the name is
  split for you).
- E-mail only: send `email` to `/v2/gender/by-email-address`.
- A one-off list: [upload the CSV or Excel file](https://gender-api.com/en/bulk-gender-lookup).
- Official clients for Python and eight other languages: <https://gender-api.com/en/clients>
  (Python: `pip install gender-api-client`).
