pythonpandasredispyarrowpy-redis

How to set/get Pandas dataframes into Redis using pyarrow


Using

dd = {'ID': ['H576','H577','H578','H600', 'H700'],
      'CD': ['AAAAAAA', 'BBBBB', 'CCCCCC','DDDDDD', 'EEEEEEE']}
df = pd.DataFrame(dd)

Pre Pandas 0.25, this below worked.

set:  redisConn.set("key", df.to_msgpack(compress='zlib'))
get:  pd.read_msgpack(redisConn.get("key"))

Now, there are deprecated warnings..

FutureWarning: to_msgpack is deprecated and will be removed in a future version.
It is recommended to use pyarrow for on-the-wire transmission of pandas objects.

The read_msgpack is deprecated and will be removed in a future version.
It is recommended to use pyarrow for on-the-wire transmission of pandas objects.

How does pyarrow work? And, how do I get pyarrow objects into and back from Redis.

reference: How to set/get pandas.DataFrame to/from Redis?


Solution

  • Here's a full example to use pyarrow for serialization of a pandas dataframe to store in redis

    apt-get install python3 python3-pip redis-server
    pip3 install pandas pyarrow redis
    

    and then in python

    import pandas as pd
    import pyarrow as pa
    import redis
    
    df=pd.DataFrame({'A':[1,2,3]})
    r = redis.Redis(host='localhost', port=6379, db=0)
    
    context = pa.default_serialization_context()
    r.set("key", context.serialize(df).to_buffer().to_pybytes())
    context.deserialize(r.get("key"))
       A
    0  1
    1  2
    2  3
    

    I just submitted PR 28494 to pandas to include this pyarrow example in the docs.

    Reference docs: