python - 在python中将行向量附加到保存的数组
问题描述
我正在循环中生成行向量。例如:
import random
for x in range(100):
print([random.randint(0,10), random.randint(0,10), random.randint(0,10)])
如何将这些行一次(或以预定义的块大小)附加到保存到文件(例如使用 HDF5 或类似文件)的(最初为空)数组中?我知道数组需要的列数,但事先不知道最终数组将有多少行。
解决方案
import random
vec_array = []
for x in range(100):
row = [random.randint(0,10), random.randint(0,10), random.randint(0,10)]
print(row)
vec_array.append(row)
print(vec_array)
我不确定“已保存的数组”是什么意思。你在某处导出这个数组?要将此数组保存为 JSON,您可以使用:
import json
with open('output.json','w+') as f:
json.dump({'vec_array':vec_array},f)
要再次加载该数据,您只需运行:
import json
with open('output.json') as f:
vec_array = json.load(f)['vec_array']
进一步阅读:
https ://docs.python.org/3/library/json.html
对于更大的数据集,SQL 数据库将是合适的:
https ://docs.python.org/3/library/sqlite3.html
如果您确定要使用 HDF5,如果超过最大大小,则必须调整数据集的大小。
https://docs.h5py.org/en/stable/high/dataset.html#reading-writing-data
https://docs.h5py.org/en/stable/high/dataset.html#resizable-datasets
推荐阅读
- sql - 如何在 SQL Server 中的多个列上应用字符串拆分功能
- ads - Google Ads 脚本和 Cookie
- angular - angular 11 ngmodel 未绑定到选择
- javascript - 如何在点击Highcharts Reactjs中的每一列时添加表格?
- wordpress - WP API 响应不显示我注册的元数据
- java - 如何从用户输入的二维数组中删除一行
- powershell - Powershell用双引号和新行替换
- java - java包如何同时以其路径和文件夹名称命名?
- asp.net-core - ASP Blazor WebAssembly 电子商务安全
- r - 我正在尝试使用 Dplyr 代码过滤我的数据,但变异、过滤和选择不起作用