json - 编码大型 numpy 数组并将其保存到 dynamodb
问题描述
我正在尝试使用 Python 构建一个 lambda 函数,并将 dict 输出保存到 dynamodb 数据库。dict 输出之一是浮点数 numpy 数组。可能已经提出了类似的问题,例如,这里使用 pickle.dumps 或 numpy.save (如何在保留矩阵维度的同时序列化 numpy 数组?)。
import boto3
import numpy as np
import pickle
# Dynamodb table example with primary keys first_name and last_name
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('users')
# Dict output example
output = {
'first_name': 'David',
'last_name': 'Adams',
'rate', np.random.rand(100000)
}
# Put dict output directly as item to dynamodb
# it will fail due to the data type dynamodb supports
table.put_item(
Item = output
)
# OR convert array to string, but the numeric array will be truncated
table.put_item(
Item = {
'first_name': output['first_name'],
'last_name': output['last_name'],
'rate': str(output['rate'])
}
)
# OR using pickle.dumps to convert numeric array to bytes.
# However, it will fail when the array length is too big, since dynamodb item has a limit of 400kb
table.put_item(
Item = {
'first_name': output['first_name'],
'last_name': output['last_name'],
'rate': pickle.dumps(output['rate'])
}
)
解决方案
推荐阅读
- python - 选择一个子项作为树中的当前项
- c - 为什么我的二叉树搜索函数不返回根地址?
- outlook-addin - Item_Load 事件:Outlook.ActiveExplorer().Selection 不为 null 但不能强制转换为 Selection(抛出异常)为什么?
- express - 在 Redis 中存储 JWT 令牌的标准做法是什么?
- android - ViewModel 不会触发 mutablelivedata 的观察者
- html - 使用 XMLHttpRequest 读取文本文件?
- python - Pytest:查找每个测试的开始和结束时间
- swagger - 对于 post 请求产生关键字类型不会成为响应标头内容类型
- shell - Angular 8 中的代码编辑器(ace 编辑器)(文本/JavaScript/sh/sh 等编辑器)
- c++ - 如何使用块更改 matrixXd 特征中的值?