在redis中存儲ndarray的示例代碼
如何在redis中存儲ndarray
在Redis中存儲NumPy數(shù)組(ndarray)通常需要將數(shù)組轉(zhuǎn)換為二進制格式,然后將其存儲為字符串。以下是使用Python和Redis-py庫的一個簡單示例:
首先,確保你已經(jīng)安裝了Redis-py庫:
pip install redis
然后,你可以使用以下代碼將NumPy數(shù)組存儲到Redis中:
import redis import numpy as np import pickle # 連接到本地Redis服務(wù)器,端口默認是6379 redis_client = redis.StrictRedis(host='localhost', port=6379, db=0) # 創(chuàng)建一個示例的NumPy數(shù)組 arr = np.array([[1, 2, 3], [4, 5, 6]]) # 將NumPy數(shù)組轉(zhuǎn)換為二進制字符串 arr_binary = pickle.dumps(arr) # 存儲二進制字符串到Redis redis_client.set('numpy_array_key', arr_binary) # 從Redis中檢索數(shù)據(jù)并轉(zhuǎn)換回NumPy數(shù)組 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數(shù)組轉(zhuǎn)換為二進制字符串,然后使用Redis-py庫的set方法將其存儲在Redis中。在檢索時,使用get方法獲取二進制字符串,并使用pickle.loads將其轉(zhuǎn)換回NumPy數(shù)組。
補充:
如何把Numpy數(shù)組存進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數(shù)組存入Redis數(shù)據(jù)庫。 Parameters ---------- key : str 鍵字符串。 numpy_ndarray : numpy.ndarray 待存儲數(shù)組。 """ shape = numpy_ndarray.shape dim = len(shape) value = struct.pack(''.join(['>I']+['I'*dim]), *((dim,)+shape)) value = base64.a85encode(value+numpy_ndarray.tobytes()) # 得轉(zhuǎn)換成字符串,不然取出時候會報一個錯 conn = redis.Redis(connection_pool=connection_pool) conn.set(key, value) conn.close() def redis_read(key: str, dtype) -> numpy.ndarray: """從Redis中讀取一個Numpy數(shù)組。 Parameters ---------- key : str 鍵字符串。 dtype : Any 指定數(shù)組元素數(shù)據(jù)類型。 Returns ------- numpy.ndarray 從Redis鍵值對取出的數(shù)組。 """ 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
經(jīng)檢驗的,存入后可以正常取出,放心食用。
到此這篇關(guān)于如何在redis中存儲ndarray的文章就介紹到這了,更多相關(guān)redis存儲ndarray內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
redis?Template.opsForValue()中方法實例詳解
這篇文章主要介紹了redis?Template.opsForValue()中方法講解,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-05-05