【问题标题】:store/load numpy array from binary files从二进制文件存储/加载 numpy 数组
【发布时间】:2010-06-16 11:03:20
【问题描述】:

我想从二进制文件中存储和加载 numpy 数组。为此,我创建了两个小函数。每个二进制文件都应该包含给定矩阵的维数。

def saveArrayToFile(data, fileName):
    with open(fileName, 'w') as file:
        a = array.array('f')
        nSamples, ndim = data.shape
        a.extend([nSamples, ndim]) # write number of elements and dimensions
        a.fromstring(data.tostring())
        a.tofile(file)


def readArrayFromFile(fileName):
    _featDesc = np.fromfile(fileName, 'f')
    _ndesc = int(_featDesc[0])
    _ndim  = int(_featDesc[1])
    _featDesc = _featDesc[2:]
    _featDesc = _featDesc.reshape([_ndesc, _ndim])

    return _featDesc, _ndesc, _ndim

如何使用函数的一个例子是:

myarr=np.array([[7, 4],[3, 9],[1, 3]])
saveArrayToFile(myarr,'myfile.txt')
_featDesc, _ndesc, _ndim = readArrayFromFile('myfile.txt')

但是,会显示“ValueError:新数组的总大小必须保持不变”的错误消息。我的数组大小可以是 MxN 和 MxM。任何建议都非常受欢迎。 我认为问题可能出在 saveArrayToFile 函数中。

祝你好运,

哈维尔

【问题讨论】:

    标签: python file binaryfiles


    【解决方案1】:

    使用 numpy.save(和 numpy.load)将 numpy 数组转储(检索)到(从)二进制文件。

    【讨论】:

    • 好的,谢谢!但是,我确实需要将数组的 MxN 维度存储到文件中。
    • 将文件命名为 myfile_MxN.npy 这样就足够了吗?
    • @Javier:如果您想在不读取整个文件的情况下获取该数据,我可以理解为什么您可能希望将数组的维度保存在文件的前几个字节中。但是,_featDesc, _ndesc, _ndim = readArrayFromFile('myfile.txt') 建议您正在阅读整个文件(不要偷看标题位)。那么为什么不简单地使用arr=np.load(...),然后使用_ndesc,_ndim = arr.shape
    猜你喜欢
    • 2021-06-28
    • 2013-07-08
    • 1970-01-01
    • 2013-06-10
    • 2014-01-27
    • 2017-07-27
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    相关资源
    最近更新 更多