API reference¶
Signatures, parameters and return values of the public functions. Most code
needs only read_gtf(); the table maps other tasks to
their functions.
| Task | Interface |
|---|---|
| Read a file with expanded attributes and output conversion | read_gtf() |
| Write annotation rows | write_gtf() |
| Read fixed fields without attribute expansion | parse_gtf() |
| Parse and expand attribute strings | parse_gtf_and_expand_attributes() |
Deprecated compatibility wrapper (removal planned for 4.0): parse_gtf() plus a convert progress stage |
parse_gtf_pandas() |
| Expand a collection of attribute strings | expand_attribute_strings() |
| Synthesize missing parent rows explicitly | create_missing_features() |
| Summarize required-feature completeness per transcript | transcript_completeness() |
| Attach per-transcript completeness columns to a GTF frame | attach_transcript_completeness() |
read_gtf ¶
Read and parse GTF genomic annotation files into DataFrames or dicts.
parse_with_polars_lazy ¶
parse_with_polars_lazy(filepath_or_buffer, split_attributes=True, features=None, fix_quotes_columns=None)
Deprecated: read eagerly and return an optional Polars LazyFrame.
Despite its name, the whole file is read before this function returns,
so nothing is scanned lazily. The exact equivalent is
polars.from_pandas(parse_gtf(...)).lazy(), which keeps the unexpanded
attribute and attribute_split columns this function returns. For
attributes expanded into columns (with read_gtf's version-column casts),
use read_gtf(..., result_type="polars").lazy() instead.
Install gtfparse[polars] to use this compatibility adapter.
Deprecated since 3.2.0; will be removed in gtfparse 4.0.
Parameters:
-
filepath_or_buffer–Passed to parse_gtf unchanged.
-
split_attributes–Passed to parse_gtf unchanged.
-
features–Passed to parse_gtf unchanged.
-
fix_quotes_columns–Passed to parse_gtf unchanged.
Returns:
-
LazyFrame–A lazy view of the frame parse_gtf returns, already held in memory.
Warns:
-
DeprecationWarning–On every call.
parse_gtf ¶
parse_gtf(filepath_or_buffer, split_attributes=True, features=None, fix_quotes_columns=None, *, progress_callback=None)
Read the fixed GTF columns, preserving raw attribute text.
Parameters:
-
filepath_or_buffer(str, path-like, or binary/text buffer) –GTF file (may be gzip compressed) or an open stream such as StringIO.
-
split_attributes(bool, default:True) –If True, add an
attribute_splitlist column with the quoted key/value pairs of each row's attribute field kept intact. -
features(set of str or None, default:None) –Keep only rows whose
featureis in this set. -
fix_quotes_columns(list of str or None, default:None) –Legacy semicolon cleanup for these columns; disabled by default.
-
progress_callback(callable, default:None) –Follows read_gtf's callback contract and emits only the
readstage.
Returns:
-
DataFrame–One row per feature with the nine columns in
REQUIRED_COLUMNS, plusattribute_splitwhen requested.
Raises:
-
ParsingError–If the input is empty or a line is malformed.
parse_gtf_pandas ¶
parse_gtf_pandas(*args, **kwargs)
Deprecated: like parse_gtf, also reporting a convert progress stage.
Kept for compatibility from when parse_gtf returned Polars; parse_gtf now
returns pandas itself, so the conversion stage does no work. Use
parse_gtf instead. The convert progress events are still emitted
while this function remains.
Deprecated since 3.2.0; will be removed in gtfparse 4.0.
Parameters:
-
*args–Passed to parse_gtf unchanged, including
progress_callback. -
**kwargs–Passed to parse_gtf unchanged, including
progress_callback.
Returns:
-
DataFrame–The same frame parse_gtf returns.
Warns:
-
DeprecationWarning–On every call.
parse_gtf_and_expand_attributes ¶
parse_gtf_and_expand_attributes(filepath_or_buffer, restrict_attribute_columns=None, features=None, *, progress_callback=None)
Parse a GTF into a pandas DataFrame and then expand the 'attribute' column into multiple columns. This expansion happens by replacing strings of semi-colon separated key-value values in the 'attribute' column with one column per distinct key, with a list of values for each row (using empty strings for rows where the key didn't occur).
Parameters:
-
filepath_or_buffer(str or buffer object) – -
restrict_attribute_columns(list/set of str or None, default:None) –If given, then only use these attribute columns.
-
features(set or None, default:None) –Ignore entries which don't correspond to one of the supplied features
-
progress_callback(callable, default:None) –Follows read_gtf's callback contract, emitting read and attributes stages.
read_gtf ¶
read_gtf(filepath_or_buffer, expand_attribute_column=True, infer_biotype_column=False, column_converters=None, column_cast_types=None, usecols=None, features=None, result_type='pandas', attribute_aliases=None, cast_version_columns=True, *, flag_incomplete_transcripts=False, progress_callback=None)
Parse a GTF into a Polars DataFrame, pandas DataFrame, or dictionary.
Parameters:
-
filepath_or_buffer(str or buffer object) –Path to GTF file (may be gzip compressed) or buffer object such as StringIO
-
expand_attribute_column(bool, default:True) –Replace strings of semi-colon separated key-value values in the 'attribute' column with one column per distinct key, with a list of values for each row (using empty strings for rows where the key didn't occur).
-
infer_biotype_column(bool, default:False) –Due to the annoying ambiguity of the second GTF column across multiple Ensembl releases, figure out if an older GTF's source column is actually the gene_biotype or transcript_biotype.
-
column_converters(dict, default:None) –Dictionary mapping column names to conversion functions. Will replace empty strings with None and otherwise passes them to given conversion function.
-
column_cast_types(dict, default:None) –Dictionary mapping column names to dtypes. Will cast columns to given pandas-compatible types.
-
usecols(list of str or None, default:None) –Restrict which columns are loaded to the give set. If None, then load all columns.
-
features(set of str or None, default:None) –Drop rows which aren't one of the features in the supplied set
-
result_type(One of 'pandas', 'dict', or 'polars' (requires the optional extra), default:'pandas') –Return a pandas DataFrame by default. Polars output requires
pip install 'gtfparse[polars]'; dictionary output is also supported. -
attribute_aliases(dict of str -> str, default:None) –Maps alias attribute names onto canonical ones. After attributes are expanded into columns, each alias column is renamed to its canonical name when the canonical column is absent. If both are present the alias is dropped and a warning is logged. Pass
GENCODE_BIOTYPE_ALIASESto normalize a GENCODE GTF'sgene_type/transcript_typeonto Ensembl'sgene_biotype/transcript_biotype. -
cast_version_columns(bool, default:True) –When True (default), cast the well-known integer version attribute columns (
gene_version,transcript_version,protein_version,exon_version) from strings to pandas nullable Int64 when present. Set to False to keep them as strings. -
flag_incomplete_transcripts(bool, default:False) –When True, aggregate over rows sharing
transcript_idand attach nullable boolean columnshas_start_codon,has_stop_codon, andtranscript_complete. A transcript withCDSrows is complete when bothstart_codonandstop_codonrows are present; non-coding transcripts (withoutCDS) are marked complete; rows without atranscript_idreceivepd.NA. Requiresexpand_attribute_column=True. Defaults to False. -
progress_callback(callable, default:None) –Called synchronously as
callback(stage, completed, total). Counts are rows retained after feature filtering. Stages occur in order:read,attributes(if expanded), andconvert. Read and convert emit(stage, 0, None)before work and(stage, rows, rows)after success; None means the total is unknown, so show an indeterminate indicator. Attribute expansion reports a known total at the start, every 10,000 rows, and at completion (one event for zero rows). Exceptions, including those raised by the callback, propagate without reporting completion of the failed stage. Default: no callback or UI.
write_gtf ¶
Serialize pandas or Polars feature DataFrames back to GTF files.
write_gtf ¶
write_gtf(df, path, header_lines=None)
Write a DataFrame of genomic features back out to a GTF file.
This is the inverse of read_gtf. A DataFrame produced by
read_gtf (whether the attribute column was expanded into one column per
key or left as a raw attribute string) can be written back out and
re-read to recover an equivalent DataFrame.
Parameters:
-
df(DataFrame or DataFrame) –Feature rows to write. Must contain the fixed GTF columns (seqname, source, feature, start, end, score, strand, frame). Any additional column is written as an attribute, except a column literally named
attribute, which is treated as a pre-formatted attribute string and emitted verbatim. -
path(str or Path) –Destination file path. Any existing file is overwritten. If the path ends in
.gzthe output is gzip-compressed (mirroring read_gtf, which transparently reads gzip-compressed GTFs). -
header_lines(iterable of str, default:None) –Lines to write at the top of the file before any feature rows, e.g.
["##description: example", "##provider: GENCODE"]. Each is written verbatim on its own line, so include a leading#if you want it to be parsed back as a comment.
Notes
Attribute values are enclosed in double quotes, so spaces, apostrophes, and semicolons round-trip. This writer does not escape embedded double quotes, tabs, or newlines; values containing those characters are outside its round-trip guarantees. Empty and missing attributes are both omitted.
parse_gtf ¶
parse_gtf(filepath_or_buffer, split_attributes=True, features=None, fix_quotes_columns=None, *, progress_callback=None)
Read the fixed GTF columns, preserving raw attribute text.
Parameters:
-
filepath_or_buffer(str, path-like, or binary/text buffer) –GTF file (may be gzip compressed) or an open stream such as StringIO.
-
split_attributes(bool, default:True) –If True, add an
attribute_splitlist column with the quoted key/value pairs of each row's attribute field kept intact. -
features(set of str or None, default:None) –Keep only rows whose
featureis in this set. -
fix_quotes_columns(list of str or None, default:None) –Legacy semicolon cleanup for these columns; disabled by default.
-
progress_callback(callable, default:None) –Follows read_gtf's callback contract and emits only the
readstage.
Returns:
-
DataFrame–One row per feature with the nine columns in
REQUIRED_COLUMNS, plusattribute_splitwhen requested.
Raises:
-
ParsingError–If the input is empty or a line is malformed.
parse_gtf_and_expand_attributes ¶
parse_gtf_and_expand_attributes(filepath_or_buffer, restrict_attribute_columns=None, features=None, *, progress_callback=None)
Parse a GTF into a pandas DataFrame and then expand the 'attribute' column into multiple columns. This expansion happens by replacing strings of semi-colon separated key-value values in the 'attribute' column with one column per distinct key, with a list of values for each row (using empty strings for rows where the key didn't occur).
Parameters:
-
filepath_or_buffer(str or buffer object) – -
restrict_attribute_columns(list/set of str or None, default:None) –If given, then only use these attribute columns.
-
features(set or None, default:None) –Ignore entries which don't correspond to one of the supplied features
-
progress_callback(callable, default:None) –Follows read_gtf's callback contract, emitting read and attributes stages.
parse_gtf_pandas ¶
parse_gtf_pandas(*args, **kwargs)
Deprecated: like parse_gtf, also reporting a convert progress stage.
Kept for compatibility from when parse_gtf returned Polars; parse_gtf now
returns pandas itself, so the conversion stage does no work. Use
parse_gtf instead. The convert progress events are still emitted
while this function remains.
Deprecated since 3.2.0; will be removed in gtfparse 4.0.
Parameters:
-
*args–Passed to parse_gtf unchanged, including
progress_callback. -
**kwargs–Passed to parse_gtf unchanged, including
progress_callback.
Returns:
-
DataFrame–The same frame parse_gtf returns.
Warns:
-
DeprecationWarning–On every call.
expand_attribute_strings ¶
expand_attribute_strings(attribute_strings, quote_char="'", missing_value='', usecols=None, *, progress_callback=None)
The last column of GTF has a variable number of key value pairs of the format: "key1 value1; key2 value2;" Parse these into a dictionary mapping each key onto a list of values, using missing_value for any row where the key was missing.
Parameters:
-
attribute_strings(sequence of str or sequences of str) –Raw attribute fields or already separated key/value pairs per row. None represents a row with no attributes.
-
quote_char(str, default:"'") –Additional surrounding quote character to remove from values. Standard double quotes are always recognized.
-
missing_value(any, default:'') –If an attribute is missing from a row, give it this value.
-
usecols(list of str or None, default:None) –If not None, then only expand columns included in this set, otherwise use all columns.
-
progress_callback(callable, default:None) –Called as
callback("attributes", completed_rows, total_rows)at the start, every 10,000 rows, and at completion. An empty input emits one("attributes", 0, 0)event. Callback exceptions propagate.
Returns:
-
OrderedDict–Column-to-value-list mappings, in the order the columns appeared in the attribute strings.
create_missing_features ¶
Synthesize missing parent features (such as genes or transcripts) from child GTF rows.
create_missing_features ¶
create_missing_features(dataframe, unique_keys=None, extra_columns=None, missing_value=None, *, strict='best_effort', required_attributes_per_feature=None)
Helper function used to construct a missing feature such as 'transcript' or 'gene'. Some GTF files only have 'exon' and 'CDS' entries, but have transcript_id and gene_id annotations which allow us to construct those missing features.
Parameters:
-
dataframe(DataFrame) –Should contain at least the core GTF columns, such as "seqname", "start", and "end"
-
unique_keys(dict, default:None) –Mapping from feature names to the name of the column which should act as a unique key for that feature. Example: {"gene": "gene_id"}
-
extra_columns(dict, default:None) –By default the constructed feature row will include only the 8 core columns and its unique key. Any other columns that should be included should be associated with the feature name in this dict.
-
missing_value(any, default:None) –Which value to fill in for columns that we don't infer values for.
-
strict((best_effort, warn, 'raise'), default:"best_effort") –Policy when a group lacks required attributes or has inconsistent parent metadata (conflicting
seqname/strandor missing/conflictingextra_columnsvalues):"best_effort"(default): synthesize rows with available metadata, filling ambiguous or missing extra columns withmissing_value. Groups that failrequired_attributes_per_featureare skipped."warn": log a warning and skip the synthesized row."raise": raiseValueError.
-
required_attributes_per_feature(dict of str -> iterable of str, default:None) –Mapping from feature name to attribute columns that must have at least one non-null, non-empty value among a group's child rows in order to synthesize that parent row. Example:
{"transcript": {"exon_id"}}.
Returns:
-
DataFrame–Original rows (converted to pandas if necessary) together with the extra rows created for missing features.
transcript_completeness ¶
transcript_completeness(dataframe, *, required_features=DEFAULT_REQUIRED_CODING_FEATURES, coding_feature='CDS', transcript_id_column='transcript_id')
Compute per-transcript completeness of required coding features.
A transcript with one or more coding_feature rows (default "CDS")
is considered complete when every feature named in required_features
(default ("start_codon", "stop_codon")) also appears for that
transcript_id. Non-coding transcripts (those without any
coding_feature row) are marked transcript_complete = True.
Parameters:
-
dataframe(DataFrame or DataFrame) –Parsed GTF table containing
featureandtranscript_id_column. -
required_features(sequence of str, default:DEFAULT_REQUIRED_CODING_FEATURES) –Feature names required whenever a transcript has
coding_featurerows. Defaults to("start_codon", "stop_codon"). -
coding_feature(str, default:'CDS') –Feature name that identifies coding transcripts. Defaults to
"CDS". -
transcript_id_column(str, default:'transcript_id') –Column containing transcript identifiers. Defaults to
"transcript_id".
Returns:
-
DataFrame–DataFrame indexed by non-empty
transcript_idvalues with boolean columnshas_cds(orhas_<coding_feature.lower()>),has_<feature>for each feature inrequired_features, andtranscript_complete.
attach_transcript_completeness ¶
attach_transcript_completeness(dataframe, *, required_features=DEFAULT_REQUIRED_CODING_FEATURES, coding_feature='CDS', transcript_id_column='transcript_id')
Attach per-transcript feature completeness columns to a GTF DataFrame.
Adds nullable boolean columns has_<feature> for each feature in
required_features (default has_start_codon and has_stop_codon)
plus transcript_complete. Rows without a transcript_id (such as
gene rows) receive pd.NA.
Parameters:
-
dataframe(DataFrame or DataFrame) –Parsed GTF table containing
featureandtranscript_id_column. -
required_features(sequence of str, default:DEFAULT_REQUIRED_CODING_FEATURES) –Feature names required whenever a transcript has
coding_featurerows. Defaults to("start_codon", "stop_codon"). -
coding_feature(str, default:'CDS') –Feature name that identifies coding transcripts. Defaults to
"CDS". -
transcript_id_column(str, default:'transcript_id') –Column containing transcript identifiers. Defaults to
"transcript_id".
Returns:
-
DataFrame–Copy of
dataframewith the completeness columns attached.
ParsingError ¶
Bases: Exception
Raised when GTF input is empty or malformed.
For example, a non-comment line without exactly nine tab-separated fields,
or a fixed column (such as start) whose value can't be converted to the
column's type.