如何在redis中存储ndarray
在redis中存储numpy数组(ndarray)通常需要将数组转换为二进制格式,然后将其存储为字符串。以下是使用python和redis-py库的一个简单示例:
首先,确保你已经安装了redis-py库:
pip install redis
然后,你可以使用以下代码将numpy数组存储到redis中:
import redis
import numpy as np
import pickle
# 连接到本地redis服务器,端口默认是6379
redis_client = redis.strictredis(host='localhost', port=6379, db=0)
# 创建一个示例的numpy数组
arr = np.array([[1, 2, 3], [4, 5, 6]])
# 将numpy数组转换为二进制字符串
arr_binary = pickle.dumps(arr)
# 存储二进制字符串到redis
redis_client.set('numpy_array_key', arr_binary)
# 从redis中检索数据并转换回numpy数组
stored_data = redis_client.get('numpy_array_key')
if stored_data:
retrieved_arr = pickle.loads(stored_data)
print("retrieved numpy array:")
print(retrieved_arr)
else:
print("key not found in redis.")在这个例子中,pickle模块被用来将numpy数组转换为二进制字符串,然后使用redis-py库的set方法将其存储在redis中。在检索时,使用get方法获取二进制字符串,并使用pickle.loads将其转换回numpy数组。
补充:
如何把numpy数组存进redis
import (base64, struct, numpy, redis)
host = 'localhost'
port = 6379
connection_pool = redis.connectionpool(host=host, port=port, decode_responses=true) # 连接池
def redis_save(key: str, numpy_ndarray: numpy.ndarray) -> none:
"""将numpy数组存入redis数据库。
parameters
----------
key : str
键字符串。
numpy_ndarray : numpy.ndarray
待存储数组。
"""
shape = numpy_ndarray.shape
dim = len(shape)
value = struct.pack(''.join(['>i']+['i'*dim]), *((dim,)+shape))
value = base64.a85encode(value+numpy_ndarray.tobytes()) # 得转换成字符串,不然取出时候会报一个错
conn = redis.redis(connection_pool=connection_pool)
conn.set(key, value)
conn.close()
def redis_read(key: str, dtype) -> numpy.ndarray:
"""从redis中读取一个numpy数组。
parameters
----------
key : str
键字符串。
dtype : any
指定数组元素数据类型。
returns
-------
numpy.ndarray
从redis键值对取出的数组。
"""
size = 4
conn = redis.redis(connection_pool=connection_pool)
bytes = base64.a85decode(conn.get(key))
conn.close()
dim = struct.unpack('>i', bytes[:1*size])[0]
shape = struct.unpack('>%s' % ('i'*dim), bytes[1*size:(dim+1)*size])
ret = numpy.frombuffer(
bytes,
offset=(dim+1)*size,
dtype=dtype
).reshape(shape)
return ret经检验的,存入后可以正常取出,放心食用。
到此这篇关于如何在redis中存储ndarray的文章就介绍到这了,更多相关redis存储ndarray内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论