HDF5 and Pickle

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

This page covers two older ways of saving a DataFrame that you will still meet in notebooks and scripts: HDF5 files written through PyTables (to_hdf, read_hdf and HDFStore), and Python’s own pickle format (to_pickle and read_pickle). Both are convenient, and both come with real limits. HDF5 is awkward with new dtypes and is not thread-safe for writing. Pickle can run arbitrary code when it is loaded. For most new work Parquet is the better default; this page explains when HDF5 or pickle is still reasonable and how to avoid their traps. The last part covers the readers for files from Stata, SAS and SPSS.

The page targets Python 3.13 or 3.14 and pandas 3.1 and was checked in October 2026. Every example was run on pandas 3.1.0 with PyTables 3.11.1 and NumPy 2.5.4 on Python 3.13.

HDF5 with PyTables

HDF5 is a hierarchical container: a file holds groups (like directories) and datasets (arrays), each with metadata. pandas stores its objects inside it using the PyTables library and its own layout. That is why read_hdf and HDFStore read files written by pandas but not arbitrary HDF5 files. To read a general HDF5 file from another tool use h5py or PyTables directly.

python -m pip install "pandas>=3.1" tables

Two storage formats

to_hdf and HDFStore.put can store an object in one of two formats:

fixed (the default) table

How to ask

format="fixed" or "f"

format="table" or "t"

Write and read speed

Fastest to write, slightly faster to read

Slower to write than fixed

Append rows later

No

Yes, with append or HDFStore.append

Query part of it with where

No: raises TypeError

Yes, on the index and on data_columns

Delete rows

No

Yes

Non-unique column names

Not supported

Not covered by the official guide; use unique names

The sample table for this page:

import numpy as np
import pandas as pd

df = pd.DataFrame({
    "order_id": np.arange(1, 7),
    "country": ["ES", "FR", "ES", "DE", "FR", "ES"],
    "amount": [10.5, 20.0, 5.0, 7.25, 3.0, 99.9],
    "ordered": pd.to_datetime([
        "2026-01-01", "2026-01-02", "2026-02-01",
        "2026-02-15", "2026-03-01", "2026-03-02",
    ]),
})

The fixed format

df.to_hdf("fixed.h5", key="orders")           # format="fixed" by default
print(pd.read_hdf("fixed.h5", "orders").dtypes)

try:
    pd.read_hdf("fixed.h5", "orders", where="amount > 5")
except TypeError as exc:
    print(exc)
order_id             int64
country                str
amount             float64
ordered     datetime64[us]
dtype: object
cannot pass a where specification when reading from a Fixed format store. this store must be selected in its entirety

A fixed store must be read in full. Use it for a quick snapshot of a whole table that you will read whole.

The table format and queries

format="table" stores the data so that parts of it can be selected on disk, without loading the file. Only the index and the columns you list in data_columns can appear in a where expression; other columns are stored but cannot be filtered on.

df.to_hdf("table.h5", key="orders", format="table", data_columns=["country", "amount"])

print(pd.read_hdf("table.h5", "orders", where="country == 'ES' & amount > 6"))
print(pd.read_hdf("table.h5", "orders", where="index < 3", columns=["amount"]))
   order_id country  amount    ordered
0         1      ES    10.5 2026-01-01
5         6      ES    99.9 2026-03-02
   amount
0    10.5
1    20.0
2     5.0

The where string uses & and | for "and" and "or", the comparison operators, and the word index for the index. A reference to an unknown name (typically a column that is not in data_columns) raises ValueError, and an invalid expression raises SyntaxError. start and stop apply before where, not after it, so select(..., where="A > 0", stop=1) can return nothing even though matching rows exist; this is different from SQL LIMIT.

HDFStore: appending, several tables and a context manager

with pd.HDFStore("table.h5", mode="a") as store:
    more = df.assign(order_id=df["order_id"] + 10)
    store.append("orders", more, data_columns=["country", "amount"])
    print(store.keys(), store.get_storer("orders").nrows)
    print(store.select("orders", where="country == 'DE'"))
    print(store.select_column("orders", "country").unique())

    store.put("raw/clean", df, format="table")     # keys can be hierarchical
    print(store.keys())
['/orders'] 12
   order_id country  amount    ordered
3         4      DE    7.25 2026-02-15
3        14      DE    7.25 2026-02-15
<ArrowStringArray>
['ES', 'FR', 'DE']
Length: 3, dtype: str
['/orders', '/raw/clean']

Notes on this example:

  • The with block closes the file even if an error occurs; store.is_open tells you the state. Always close a store, so that everything is flushed to disk.

  • append requires the same columns in the same order every time, and the data_columns cannot be changed after the first write. The index values are not reset, which is why the DE row appears with index 3 twice.

  • select_column reads just one data column, which is a cheap way to list the distinct keys.

  • Keys such as raw/clean create nested groups and are always absolute. store.remove("raw") deletes everything below the key. Attribute access (store.raw.clean) does not work for hierarchical keys; use store.get("raw/clean").

  • Appending to an object that was stored as fixed raises ValueError ("Can only append to Tables"). Write it with format="table" first, or set pd.set_option("io.hdf.default_format", "table").

  • In pandas 3.1 HDFStore.put warns that the default of track_times will change from True to False in a future version. Pass track_times=False to get files that are byte-identical for identical data, which helps caching and version control.

Strings and dtypes

In a table, string columns are stored at a fixed width taken from the first write. A longer string in a later append is an error; reserve room with min_itemsize:

with pd.HDFStore("w.h5", mode="w") as store:
    store.append("t", pd.DataFrame({"s": ["ab"]}))
    try:
        store.append("t", pd.DataFrame({"s": ["abcdefgh"]}))
    except ValueError as exc:
        print(str(exc).splitlines()[0])

    store.append("u", pd.DataFrame({"s": ["ab"]}), min_itemsize={"s": 50})
Trying to store a string with len [8] in [values_block_0] column but

The same section of the official guide documents further restrictions:

  • Pandas extension dtypes such as Int64, Float64, boolean, IntervalDtype and SparseDtype cannot be written; the call raises NotImplementedError. Convert to NumPy dtypes first, for example with astype("float64") after handling the missing values (see Nullable Integer and Boolean).

  • The index keyword is reserved and cannot be a level or column name, and column names that are not valid Python identifiers produce a NaturalNameWarning.

  • Object columns that PyTables cannot represent natively are pickled, which is slow (a PerformanceWarning) and brings the security risk described below.

  • A time zone is stored by its name. Reading with a different time-zone database version can shift values, so keep the libraries the same on both sides or store UTC.

  • All-NaN rows are kept by default. The dropna keyword of to_hdf, put and append is deprecated in pandas 3.1 (it emits a Pandas4Warning); call df.dropna() before writing instead.

Compression

Without compression, a 200,000-row table of 4 small integer columns used 8.2 MB. With a compression level it shrinks a lot:

import os

big = pd.DataFrame(np.random.default_rng(0).integers(0, 10, size=(200_000, 4)), columns=list("abcd"))
for kw in [{}, {"complevel": 5, "complib": "blosc:zstd"}, {"complevel": 5, "complib": "zlib"}]:
    big.to_hdf("big.h5", key="b", format="table", mode="w", **kw)
    print(kw, os.path.getsize("big.h5"))
{} 8210230
{'complevel': 5, 'complib': 'blosc:zstd'} 631208
{'complevel': 5, 'complib': 'zlib'} 666760

complib takes effect only when complevel is greater than 0. Passing complib="zlib" alone writes uncompressed data and emits UserWarning: complib='zlib' was specified without complevel. An unknown complib raises ValueError, and a library missing from your PyTables build falls back to zlib.

Limits to know before choosing HDF5

  • No concurrent writing. HDFStore is not thread-safe for writes, and two writers corrupt the file. Reading from several threads or processes at once is fine.

  • Space is not reclaimed. Deleting rows or rewriting a table leaves the file the same size. Repack with the ptrepack tool that ships with PyTables.

  • Fragile for sharing. The layout is specific to pandas and PyTables; Spark, DuckDB and most other tools read Parquet but not these files.

  • Writes are chunked. The default chunksize is 50,000 rows; give expectedrows on the first append when you know the final size.

  • An empty DataFrame in table format is not written; pandas emits a UserWarning. Use format="fixed" to store an empty object.

Pickle

to_pickle serialises any pandas object with Python’s pickle module and read_pickle loads it back. It preserves every dtype, the index, categories, extension arrays, and even Python objects stored in object columns, with no conversion rules to learn.

df.to_pickle("orders.pkl")
print(pd.read_pickle("orders.pkl").equals(df))
True

The default protocol is 5. compression="infer" chooses the codec from the file extension:

import os

for ext in ["gz", "bz2", "xz"]:
    df.to_pickle(f"orders.pkl.{ext}")
    print(ext, os.path.getsize(f"orders.pkl.{ext}"), pd.read_pickle(f"orders.pkl.{ext}").equals(df))

df.to_pickle("fast.pkl.gz", compression={"method": "gzip", "compresslevel": 1})
gz 903 True
bz2 971 True
xz 928 True

The supported codecs are gzip, bz2, xz and zstd for reading and writing, and zip for reading only (the archive must contain exactly one file). A dictionary with a required "method" key passes options such as compresslevel to the underlying library. On Python 3.13 the zstd codec needs the optional zstandard package and raises ImportError without it.

Why pickle is dangerous

Unpickling can execute arbitrary code. A pickle file does not store data only; it stores instructions for rebuilding objects, and an attacker can make those instructions call any function. This harmless demonstration prints a message while loading:

class Demo:
    def __reduce__(self):
        return (print, ("code ran while loading the pickle",))

pd.to_pickle(Demo(), "demo.pkl")
pd.read_pickle("demo.pkl")
code ran while loading the pickle

Replace print with a call that deletes files or sends data out, and a downloaded "dataset" becomes an attack. The pandas documentation warns that loading pickled data from untrusted sources is unsafe, and the same applies to HDF5 files that contain pickled object columns. The rules:

  • Never call read_pickle or read_hdf on a file that came from the internet, an email or a person you do not control.

  • Do not unpickle from a shared folder that other people can write to.

  • Prefer Parquet or Feather for data that crosses a trust boundary.

  • For trained scikit-learn models see Model Persistence and Security.

Compatibility

read_pickle is only guaranteed to read pickles written by the current or the previous major pandas version. In pandas 3.x the earliest supported pickle comes from pandas 2.0.0. A pickle is also tied to your Python version and the classes it contains, so it is a short-term cache or a checkpoint, never an archive. Stored data that must be read in two years belongs in Parquet.

Stata, SAS and SPSS

Files from statistical packages are read with dedicated functions. Stata is the only one of the three that pandas can also write; SAS and SPSS files are read-only.

Format Read Write Extra dependency

Stata .dta

read_stata, StataReader

DataFrame.to_stata

None

SAS .sas7bdat and XPORT .xpt

read_sas

Not supported

None

SPSS .sav

read_spss

Not supported

pyreadstat

Stata

to_stata writes a .dta file and read_stata reads it back. Stata has no 64-bit integer type, so integers that fit come back as int32; categoricals are stored as value labels and restored as category; dates need an entry in convert_dates ("td" is a daily date) and come back as datetime64[s]. The default version=114 limits strings to 244 bytes and Latin-1 text; version=118 writes Unicode and allows long strings through convert_strl:

import numpy as np
import pandas as pd

orders = pd.DataFrame({
    "id": [1, 2, 3],
    "country": ["ES", "DE", "FR"],
    "amount": [25.0, np.nan, 15.5],
    "ordered": pd.to_datetime(["2024-01-05", "2024-03-17", "2024-06-30"]),
    "size": pd.Categorical(["S", "M", "S"], categories=["S", "M", "L"]),
})
orders.to_stata("orders.dta", write_index=False, version=118, convert_dates={"ordered": "td"},
                variable_labels={"amount": "Order amount in EUR"})

back = pd.read_stata("orders.dta")
print(back)
print(back.dtypes)
with pd.io.stata.StataReader("orders.dta") as reader:
    print(reader.variable_labels()["amount"])
    print(reader.value_labels())
print(pd.read_stata("orders.dta", convert_categoricals=False)["size"].tolist())
with pd.read_stata("orders.dta", chunksize=2) as reader:
    print([len(chunk) for chunk in reader])
   id country  amount    ordered size
0   1      ES    25.0 2024-01-05    S
1   2      DE     NaN 2024-03-17    M
2   3      FR    15.5 2024-06-30    S
id                 int32
country              str
amount           float64
ordered    datetime64[s]
size            category
dtype: object
Order amount in EUR
{'size': {np.int32(0): 'S', np.int32(1): 'M', np.int32(2): 'L'}}
[0, 1, 0]
[2, 1]

convert_categoricals=False returns the stored codes instead of the labels, and chunksize (or iterator=True) returns a StataReader that reads the file piece by piece.

SAS

read_sas reads SAS7BDAT files and XPORT (.xpt) transport files; the format is inferred from the file extension, or set with format="sas7bdat" or format="xport". Numeric columns come back as float64. Text columns come back as raw bytes unless an encoding is given, and in pandas 3.1 leaving encoding out emits a Pandas4Warning because the default will change from None to "infer". Pass encoding="infer" to decode text with the encoding recorded in a SAS7BDAT header (XPORT files record none, so "infer" means ISO-8859-1 there). The example reads a three-row XPORT file orders.xpt with the columns ID, COUNTRY and AMOUNT:

sas = pd.read_sas("orders.xpt", encoding="infer")
print(sas)
print(sas.dtypes)
with pd.read_sas("orders.xpt", encoding="infer", chunksize=2) as reader:
    print([len(chunk) for chunk in reader])
try:
    pd.read_sas("orders.dta")
except ValueError as exc:
    print("ValueError:", exc)
    ID COUNTRY  AMOUNT
0  1.0      ES    25.0
1  2.0      DE     NaN
2  3.0      FR    15.5
ID         float64
COUNTRY        str
AMOUNT     float64
dtype: object
[2, 1]
ValueError: unable to infer format of SAS file from filename: 'orders.dta'

SPSS

read_spss reads .sav files through the optional pyreadstat package, which must be installed separately (python -m pip install pyreadstat). usecols selects columns, convert_categoricals=True (the default) turns value labels into category columns, dtype_backend chooses nullable or Arrow-backed dtypes, and since pandas 3.0 any other keyword argument is passed on to pyreadstat.read_sav. Without pyreadstat the call fails with ImportError:

try:
    survey = pd.read_spss("survey.sav", usecols=["respondent", "satisfaction"])
except ImportError as exc:
    print("ImportError:", exc)
ImportError: `Import pyreadstat` failed.  Use pip, conda, or your preferred package management tool to install the pyreadstat package.

Choosing between HDF5, pickle and Parquet

Need Choose Reason

Archive or share a table

Parquet

Open, typed, safe to read, supported everywhere

Quick cache of an expensive result in one project, on one machine

Pickle or Feather

No conversion rules; pickle also keeps arbitrary Python objects

Query slices of a very large table on disk

Parquet with filters, or HDF5 table

HDF5 table works but is single-writer and pandas-specific

Several named tables in one file

HDF5 or a database

HDFStore groups keys; a SQL database also adds concurrency (see SQL Databases)

Where older tutorials are outdated

Older statement Current situation (October 2026)

"Use to_msgpack and read_msgpack for fast serialisation" (pandas 0.x books and posts)

Removed in pandas 1.0.0. The documentation recommends pickle or Arrow IPC (Feather) instead.

"HDF5 is the standard fast format for big DataFrames" (articles around 2015 to 2018)

Parquet and Feather are now the usual choice; HDF5 keeps the single-writer and no-space-reclaim limits.

"Pickle is a safe way to share a DataFrame"

It is not safe for untrusted files, and pickles are only guaranteed to load across one pandas major version.

to_hdf(..., dropna=True) drops all-NaN rows on append

The dropna keyword is deprecated in pandas 3.1; call dropna() before writing.