table_view
Batch-pipeline
En hel DataFrame
To funktioner. Den første sender én batch og afgør, hvad der fortjener et nyt forsøg. Den anden deler en DataFrame-kolonne op i batches og fletter svarene tilbage.
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 (see below).
customers["confident"] = (customers["probability"] >= 0.9) & (customers["samples"] >= 20)
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
Fanen “Output fra testkørsel” viser det rigtige output fra en kørsel med bevidst besværlige rækker — en dublet, et indledende mellemrum, en tom celle, en tom streng, et navn, ingen har, og et, der er længere end de 50 tegn, API'et accepterer: