26

msgpack in Pandas is supposed to be a replacement for pickle.

Per the Pandas docs on msgpack:

This is a lightweight portable binary format, similar to binary JSON, that is highly space efficient, and provides good performance both on the writing (serialization), and reading (deserialization).

I find, however, that its performance does not appear to stack up against pickle.

df = pd.DataFrame(np.random.randn(10000, 100))

>>> %timeit df.to_pickle('test.p')
10 loops, best of 3: 22.4 ms per loop

>>> %timeit df.to_msgpack('test.msg')
10 loops, best of 3: 36.4 ms per loop

>>> %timeit pd.read_pickle('test.p')
100 loops, best of 3: 10.5 ms per loop

>>> %timeit pd.read_msgpack('test.msg')
10 loops, best of 3: 24.6 ms per loop

Question: Asides from potential security issues with pickle, what are the benefits of msgpack over pickle? Is pickle still the preferred method of serializing data, or do better alternatives currently exist?

5

1 Answer 1

32

Pickle is better for the following:

  1. Numerical data or anything that uses the buffer protocol (numpy arrays) (though only if you use a somewhat recent protocol=)
  2. Python specific objects like classes, functions, etc.. (although here you should look at cloudpickle)

MsgPack is better for the following:

  1. Cross language interoperation. It's an alternative to JSON with some improvements
  2. Performance on text data and Python objects. It's a decent factor faster than Pickle at this under any setting.

As @Jeff noted above this blogpost may be of interest

6
  • am I right to say that 4D panels are not supported for pickle too?
    – firefly
    Commented Nov 30, 2015 at 1:09
  • @firefly: in pandas 0.18 Panel4D is pickleable. But consider xarray instead of Panel4D.
    – mtd
    Commented Mar 17, 2016 at 17:34
  • 2
    to_msgpack() crashes for bigger size data, I am not sure about to_pickle() Commented Jul 27, 2017 at 18:08
  • what do you mean by "crashes for bigger size data" - can you expand on that? Commented Jun 13, 2019 at 13:14
  • 5
    As of 2019, MsgPack support for Pandas has been deprecated, and the recommendation is to use pyarrow instead.
    – bastibe
    Commented Jan 8, 2020 at 9:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.