[英]How to make a 2d numpy array a 3d array?
我有一個形狀為 (x, y) 的二維數組,我想將其轉換為形狀為 (x, y, 1) 的三維數組。 有沒有一個很好的 Pythonic 方法來做到這一點?
除了其他答案之外,您還可以將切片與numpy.newaxis
一起numpy.newaxis
:
>>> from numpy import zeros, newaxis
>>> a = zeros((6, 8))
>>> a.shape
(6, 8)
>>> b = a[:, :, newaxis]
>>> b.shape
(6, 8, 1)
甚至這個(它將適用於任意數量的維度):
>>> b = a[..., newaxis]
>>> b.shape
(6, 8, 1)
numpy.reshape(array, array.shape + (1,))
import numpy as np
# create a 2D array
a = np.array([[1,2,3], [4,5,6], [1,2,3], [4,5,6],[1,2,3], [4,5,6],[1,2,3], [4,5,6]])
print(a.shape)
# shape of a = (8,3)
b = np.reshape(a, (8, 3, -1))
# changing the shape, -1 means any number which is suitable
print(b.shape)
# size of b = (8,3,1)
import numpy as np
a= np.eye(3)
print a.shape
b = a.reshape(3,3,1)
print b.shape
希望這個功能可以幫助您將 2D 數組轉換為 3D 數組。
Args:
x: 2darray, (n_time, n_in)
agg_num: int, number of frames to concatenate.
hop: int, number of hop frames.
Returns:
3darray, (n_blocks, agg_num, n_in)
def d_2d_to_3d(x, agg_num, hop):
# Pad to at least one block.
len_x, n_in = x.shape
if (len_x < agg_num): #not in get_matrix_data
x = np.concatenate((x, np.zeros((agg_num - len_x, n_in))))
# main 2d to 3d.
len_x = len(x)
i1 = 0
x3d = []
while (i1 + agg_num <= len_x):
x3d.append(x[i1 : i1 + agg_num])
i1 += hop
return np.array(x3d)
如果您只想將第三個軸 (x,y) 添加到 (x,y,1),Numpy 允許您使用dstack
命令輕松完成此操作。
import numpy as np
a = np.eye(3) # your matrix here
b = np.dstack(a).T
您需要轉置 ( .T
) 以將其轉換為所需的 (x,y,1) 格式。
簡單的方法,用一些數學
首先你知道數組元素的數量,假設 100,然后在 3 個步驟中划分 100,例如:
25 * 2 * 2 = 100
或:4 * 5 * 5 = 100
import numpy as np
D = np.arange(100)
# change to 3d by division of 100 for 3 steps 100 = 25 * 2 * 2
D3 = D.reshape(2,2,25) # 25*2*2 = 100
其他方式:
another_3D = D.reshape(4,5,5)
print(another_3D.ndim)
到 4D:
D4 = D.reshape(2,2,5,5)
print(D4.ndim)
import numpy as np
# create a 2-D ndarray
a = np.array([[2,3,4], [5,6,7]])
print(a.ndim)
>> 2
print(a.shape)
>> (2, 3)
# add 3rd dimension
第一種選擇:重塑
b = np.reshape(a, a.shape + (1,))
print(b.ndim)
>> 3
print(b.shape)
>> (2, 3, 1)
第二個選項:expand_dims
c = np.expand_dims(a, axis=2)
print(c.ndim)
>> 3
print(c.shape)
>> (2, 3, 1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.