首页 > 解决方案 > 在python中将行向量附加到保存的数组

问题描述

我正在循环中生成行向量。例如:

import random
for x in range(100):
    print([random.randint(0,10), random.randint(0,10), random.randint(0,10)])

如何将这些行一次(或以预定义的块大小)附加到保存到文件(例如使用 HDF5 或类似文件)的(最初为空)数组中?我知道数组需要的列数,但事先不知道最终数组将有多少行。

标签: pythonarraysloopsappendhdf5

解决方案


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


推荐阅读