How to set/get Pandas dataframes into Redis using pyarrow

余生颓废 提交于 2020-01-01 09:55:36

问题


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?


回答1:


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:

  • https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_msgpack.html
  • https://arrow.apache.org/docs/python/ipc.html#arbitrary-object-serialization
  • https://arrow.apache.org/docs/python/memory.html#pyarrow-buffer
  • https://stackoverflow.com/a/37957490/4126114


来源:https://stackoverflow.com/questions/57949871/how-to-set-get-pandas-dataframes-into-redis-using-pyarrow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!