Przejdź do głównej zawartości

Lift a pandas DataFrame from hg19 to hg38

Use this workflow when each row of a DataFrame contains one hg19 (GRCh37) variant and you want to reuse the table with hg38 (GRCh38) annotations. The example keeps the original coordinates and sample labels, even when two rows describe the same variant or a mapping needs review.

Send variants in batches​

Install the dependencies with python -m pip install pandas requests. The input columns chr, pos, ref and alt describe one allele per row with 1-based positions. If you have comma-separated alternate alleles, split them into individual variant rows before sending the requests.

Send a JSON array of chr-pos-ref-alt strings to POST /cloud/api-public/v2/liftover?from=hg19&dest=hg38. The API returns one result per input string in order. Verify that order before attaching the results to the DataFrame. Use the candidate's destination position and alleles together because the destination reference can differ from the source reference.

import json

import pandas as pd
import requests

variants = pd.DataFrame(
[
("A", "chr6", 160585140, "T", "G"),
("B", "chr6", 160585140, "T", "G"),
("C", "chr1", 1, "A", "T"),
("D", "chr6", 160585140, "A", "G"),
],
columns=["sample", "chr", "pos", "ref", "alt"],
)

queries = [
f"{chrom}-{pos}-{ref}-{alt}"
for chrom, pos, ref, alt in variants[["chr", "pos", "ref", "alt"]]
.itertuples(index=False, name=None)
]
source = variants.rename(
columns={name: f"hg19_{name}" for name in ("chr", "pos", "ref", "alt")}
).reset_index(drop=True)
source.insert(0, "row_id", source.index)
source["query"] = queries

url = "https://api.genebe.net/cloud/api-public/v2/liftover"
records = []
with requests.Session() as session:
for start in range(0, len(queries), 50):
batch = queries[start : start + 50]
response = session.post(
url, params={"from": "hg19", "dest": "hg38"}, json=batch, timeout=30
)
response.raise_for_status()
results = response.json()["results"]
if [result["input"] for result in results] != batch:
raise ValueError(f"Unexpected liftover results for batch at row {start}")

for offset, result in enumerate(results):
candidates = result.get("candidates") or []
issues = (result.get("warnings") or []) + (result.get("errors") or [])
record = {
"row_id": start + offset,
"status": result["status"],
"issue_codes": ",".join(issue["code"] for issue in issues),
"candidates": json.dumps(candidates),
"genome": None,
"chr": None,
"pos": None,
"ref": None,
"alt": None,
}
if result["status"] == "RESOLVED" and len(candidates) == 1 and not issues:
candidate = candidates[0]
record.update(
genome=candidate["genome"],
chr=candidate["chr"],
pos=candidate["start"],
ref=candidate["ref"],
alt=candidate["alt"],
)
records.append(record)

mapping = pd.DataFrame.from_records(
records,
columns=["row_id", "status", "issue_codes", "candidates", "genome", "chr", "pos", "ref", "alt"],
)
mapping["pos"] = mapping["pos"].astype("Int64")
joined = source.merge(mapping, on="row_id", validate="one_to_one")
mapped = joined["genome"].eq("hg38")
joined.loc[mapped].to_csv("variants.hg38.csv", index=False)
joined.loc[~mapped].to_csv("liftover-review.csv", index=False)

Check the two output files​

SampleStatusDestination or review code
ARESOLVEDchr6-160164108-T-G
BRESOLVEDchr6-160164108-T-G
CUNRESOLVEDUNMAPPED_REGION
DRESOLVEDREF_MISMATCH, retained for review

This example sends every flagged result for review, including a resolved candidate with an allele mismatch. The review CSV keeps the candidate list as JSON so you can inspect all destinations for an ambiguous mapping. For files you plan to annotate, continue with batch annotation in pandas. For other input formats and warning codes, see the Liftover tool reference.