[英]Combining two numpy arrays
我有一個尺寸為(1196、14、64、1)的 numpy 數組ar1
。
我有一個尺寸為 (1196,) 的 numpy 數組ar2
。
我想將這兩者結合起來,因為我想稍后將它們洗牌。 我認為這就是 zip 的用途,但是當我將 zip 放在一起時:
ar3 = np.asarray(zip(ar1,ar2))
然后print(ar3.shape)
給出()
我也嘗試過np.concatenate
但顯然all the input array dimensions for the concatenation axis must match exactly
。
我試過np.hstack
但我得到了all the input arrays must have same number of dimensions
如何組合這兩個沿軸 0 具有相同大小的 arrays? 也許那時我不需要組合,而應該使用相同的索引分別對它們進行洗牌。
(我實際上已經使用 numpy.savez 組合並保存了這些 arrays,但是當我將此文件加載到我的代碼中時,我假設我必須先將它們分開,然后按照我的嘗試將它們重新組合成一個數組。如果我可以只需從 .npz 文件中提取一個組合數組,那就更好了)
使用np.concatenate
和np.broadcast_to
,因為連接需要所有 arrays 具有相同的維度數。 這應該可以解決問題:
x = np.ones((1196, 14, 64, 1))
y = np.arange(1196)
output = np.concatenate((x, np.broadcast_to(y[:, None, None, None], x.shape[:-1] + (1,))), axis=-1)
# output.shape --> (1196, 14, 64, 2)
In [111]: ar1 = np.ones((1196,14,62,1))
In [112]: ar2 = np.zeros((1196))
在 py3 中, zip
生成器。 你已經用list
展開它以獲得一個數組:
In [113]: np.array(zip(ar1,ar2))
Out[113]: array(<zip object at 0x7f188a465a48>, dtype=object)
那是一個單元素數組,形狀為 ()。
如果展開 zip 並創建一個數組,則結果是一個 object dtype 數組:
In [119]: A = np.array(list(zip(ar1,ar2)))
/usr/local/bin/ipython3:1: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray
#!/usr/bin/python3
In [120]: A.shape
Out[120]: (1196, 2)
In [121]: A.dtype
Out[121]: dtype('O')
In [122]: A[0,0].shape
Out[122]: (14, 62, 1)
In [123]: A[0,1].shape
Out[123]: ()
一列是 (14,62,1) arrays,另一列是ar2
值。
另一個答案建議擴展ar2
以匹配ar1
的形狀,並在最后一個軸上連接。 結果是ar1
大小的兩倍。 broadcast_to
進行“虛擬”復制(不增加內存),但這不會在連接中延續。 你得到每個ar2
值的 14*62 個副本。
但是ar2
可以廣播到 (1196,1,62,1) 並在軸 1 上連接(62x 復制),或 (1196,14,1,1) 和軸 2 連接 (14x)。 要連接,arrays 必須在除一個軸之外的所有軸上匹配。
但是對於savez
和load
,您不需要連接 arrays。 您可以單獨保存和加載它們。 savez
將它們放在單獨的npy
文件中。 savez
展示了如何加載每個數組。
你可以單獨洗牌。
做一個洗牌索引:
In [124]: idx = np.arange(1196)
In [125]: np.random.shuffle(idx)
In [126]: idx[:10]
Out[126]: array([ 561, 980, 42, 98, 1055, 375, 13, 771, 832, 787])
並將其應用於每個數組:
In [127]: ar1[idx,:,:,:];
In [128]: ar2[idx];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.