我有一个形状为(x,y(的2d数组,我想将其转换为形状为(x,y,1(的3d数组。有没有一种很好的 Python 方法来做到这一点?
除了其他答案之外,您还可以将切片与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)
如果您只想将第 3 轴 (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(格式。
你可以通过重塑来做到这一点
例如,您有一个形状为 35 x 750(二维(的数组 A,您可以使用 A.reshape(35, 25, 30( 将形状更改为 35 x 25 x 30(三维(
此处文档中的更多内容
简单的方法,有一些数学
起初你知道数组元素的数量,假设100然后通过 100 个步骤划分 3 个,例如:
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)
如果你有一个数组
a2 = np.array([[1, 2, 3.3],
[4, 5, 6.5]])
然后,您可以使用以下命令将此数组更改为 3-D shape (2, 3, 3)
数组:
a2_new = np.reshape(a2, a2.shape + (1,)) a2_new
您的输出将是:
array([[[1. ],
[2. ],
[3.3]],
[[4. ],
[5. ],
[6.5]]])
或您可以尝试:
a2.reshape(2, 3, 1)
这会将您的 2-D 数组更改为 3-D 的 shape(2, 3, 1)
。