如何解压缩 numpy.ndarray 并将其转换为另一个数组?

时间:2021-07-16 16:48:23

标签: python arrays numpy

当我尝试加载 numpy.ndarray 并将其转换为新数组时遇到了一些问题。新数组应该在 numpy.ndarray 中显示相同的数据。

首先,我使用 zip() 组合行、列和权重。

for connName in save_conns:
        conn = connections[connName]
        connListSparse = zip(conn.i[:], conn.j[:], conn.w[:])
        np.save(data_path + 'weights/' + connName + ending, connListSparse)

然后,我使用 list() 打印 connListSparse。它显示 [(0, 0, 0.1), (0, 1, 0.3), (1, 0, 0.8), (1, 1, 0.7)]。

但是,在我 np.load() .npy 文件并尝试将其转换为新数组后,它显示错误。

readout = np.load(fileName)
print(readout.shape, fileName)     #readout.shape=()
value_arr = np.zeros((n_src, n_tgt))     #n_src=2, n_tgt=2
if not readout.shape == (0,):
        value_arr[np.int32(readout[:,0]), np.int32(readout[:,1])] = readout[:,2]
return value_arr

我深入研究代码,发现当我尝试 unzipped_readout = zip(*readout) 时,它返回 TypeError: iteration over a 0-d array

我确定我的数据路径是正确的。但是新数组无法加载数据。

我使用的是 python 3.7.10、numpy 1.16.1、brian2 2.4.2。

我是这个社区的初学者。如果您想了解有关该问题的更多信息,请告诉我。谢谢。

1 个答案:

答案 0 :(得分:0)

我想知道您是否将 python zip()zip 生成的 np.savez 存档混淆了。

In [529]: zipobj = zip(np.arange(3), np.ones(3))
In [530]: zipobj
Out[530]: <zip at 0x7fc5dceb05c0>
In [531]: list(zipobj)
Out[531]: [(0, 1.0), (1, 1.0), (2, 1.0)]

保存 zipobj 与保存从中创建的列表不同。

In [532]: np.save('test.npy',zipobj)
In [533]: data = np.load('test.npy', allow_pickle=True)
In [534]: data
Out[534]: array(<zip object at 0x7fc5dc85e440>, dtype=object)

即使全部pickle,加载的zip对象也和原来的不一样,因此是空的。

In [536]: data.item()
Out[536]: <zip at 0x7fc5dc85e440>
In [537]: list(_)
Out[537]: []

但是使用 savez 我们可以保存包含数组的 zip 存档:

In [538]: np.savez('test.npz', x=np.arange(3), y=np.ones(3))
In [539]: data = np.load('test.npz')
In [540]: data
Out[540]: <numpy.lib.npyio.NpzFile at 0x7fc5dfac4eb0>

In [546]: list(data.keys())
Out[546]: ['x', 'y']
In [547]: data['x']
Out[547]: array([0, 1, 2])
In [548]: data['y']
Out[548]: array([1., 1., 1.])

您还可以使用操作系统文件存档工具查看 test.npz 包含 2 个文件,x.npyy.npy。这些加载了 data['x'] 语法。


替代储蓄:

In [549]: alist = [np.arange(3), np.ones(3)]
In [550]: np.save('test.npy',alist)
In [551]: data = np.load('test.npy', allow_pickle=True)
In [552]: data
Out[552]: 
array([[0., 1., 2.],
       [1., 1., 1.]])

由于2个数组形状匹配,它实际上保存了np.array(alist),它是一个(2,3)浮点数组。

或者,我们可以创建一个对象 dtype 数组:

In [553]: arr = np.array([None,None])
In [554]: arr[:] = alist
In [555]: arr
Out[555]: array([array([0, 1, 2]), array([1., 1., 1.])], dtype=object)
In [556]: np.save('test.npy',arr)
In [557]: data = np.load('test.npy', allow_pickle=True)
In [558]: data
Out[558]: array([array([0, 1, 2]), array([1., 1., 1.])], dtype=object)

我想知道您是否对 zip 感到困惑?也许这个简单的应用到两个列表给出了一个更清晰的想法:

In [560]: zip([1,2,3],[4,5,5])
Out[560]: <zip at 0x7fc5dce2b680>
In [561]: list(zip([1,2,3],[4,5,5]))
Out[561]: [(1, 4), (2, 5), (3, 5)]

我认为这是 transpose 的列表版本,将数组的元素配对。在 Py3 中,zip 只是设置该操作,实际执行配对需要 list(或其他迭代)。

相关问题