statfile.tools

How to read a .dta file in Python

Python has two solid readers for Stata files: pandas' built-in read_stata() and the pyreadstat library, which exposes more metadata. Here is how to use each, how to keep the labels, and a browser-based fallback for quick looks.

pandas.read_stata() — usually all you need

pandas ships with a pure-Python Stata reader: df = pandas.read_stata("data.dta"). By default it applies value labels, so coded categories arrive as pandas Categoricals with the label text. Pass convert_categoricals=False to keep the raw numeric codes instead — useful when labels are incomplete or you need to join on the codes.

Two options matter for larger files: columns=[...] reads only the variables you name, and chunksize=50_000 returns an iterator of DataFrames so you never hold the whole file in memory. Dates are converted to pandas datetimes automatically; pass convert_dates=False to keep Stata's raw numeric encoding.

pyreadstat — when you need the metadata

pyreadstat wraps the ReadStat C library and returns the data and the metadata separately: df, meta = pyreadstat.read_dta("data.dta"). The meta object carries variable labels (meta.column_labels), the full value-label dictionaries (meta.variable_value_labels), formats, and the file label — everything you need to build a codebook or preserve labels through a pipeline.

It is also faster than pandas on large files because the parsing happens in C, and it can read a slice of rows (row_limit, row_offset) for sampling huge datasets. Install it with pip install pyreadstat.

No Python at hand?

For a quick inspection — or to hand the data to someone who does not code — statfile.tools opens .dta files in the browser, shows variable and value labels in a Variable View, and converts to CSV, Excel, JSON, or SPSS .sav. The file is parsed locally and never uploaded.

Frequently asked questions

How do I keep the numeric codes instead of labels?+

Pass convert_categoricals=False to pandas.read_stata(). With pyreadstat, the codes are the default and the label dictionaries are available separately in meta.variable_value_labels.

Can pandas read new Stata 18 files?+

pandas reads dta formats 102 through 119, which covers files written by Stata 1 through Stata 18, including the modern 117/118/119 formats with strL long strings.

How do I write a .dta from Python?+

df.to_stata("out.dta", write_index=False) in pandas, or pyreadstat.write_dta(df, "out.dta") if you want to attach variable and value labels from a metadata object.

Convert this format