华域联盟 Redis 在redis中存储ndarray的示例代码

在redis中存储ndarray的示例代码

如何在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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

本文由 华域联盟 原创撰写:华域联盟 » 在redis中存储ndarray的示例代码

转载请保留出处和原文链接:https://www.cnhackhy.com/157611.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们