Python 如何使用np.newaxis转换(1,16,1)数组中的(1,16)数组?
我想转换此数组(1,16) 在(1,16,1)数组中 我试过:Python 如何使用np.newaxis转换(1,16,1)数组中的(1,16)数组?,python,arrays,numpy,Python,Arrays,Numpy,我想转换此数组(1,16) 在(1,16,1)数组中 我试过: board = board[np.newaxis, :] 但这不是加速的产出 我该怎么做呢?我的首选方法(很容易找到新轴,只涉及无内置): 正如Mad物理学家所提到的,这严格等同于使用np.newaxis:print(np.newaxis)返回None您必须将np.newaxis放在您想要这个新轴的维度的位置上 board[np.newaxis,:] -> puts the axis in the first dimensi
board = board[np.newaxis, :]
但这不是加速的产出
我该怎么做呢?我的首选方法(很容易找到新轴,只涉及无
内置):
正如Mad物理学家所提到的,这严格等同于使用
np.newaxis
:print(np.newaxis)
返回None
您必须将np.newaxis
放在您想要这个新轴的维度的位置上
board[np.newaxis,:] -> puts the axis in the first dimension [1,1,16]
board[:,np.newaxis] -> puts the axis in the second dimension [1,1,16]
board[:,:,np.newaxis] -> puts the axis in the third dimension [1,16,1]
尝试使用“重塑”:
import numpy as np
a = np.array([[4,4,4,4,4,4,4,4,4,4,4,4,0,0,0,0]])
print(a.reshape(1,16,1).shape)
此外,您还可以在中使用:
阵列升级的其他方式包括:
board[:,np.newaxis]
什么是意外的输出?@mad物理学家一个形状为(1,16,1)np.newaxis
的数组直接指向None
我知道,但我发现记住None
比np.newaxis
更容易。偏好可能会有所不同:-)我恰好同意你的偏好和你的评论。只是想让未来的读者明白。
board[np.newaxis,:] -> puts the axis in the first dimension [1,1,16]
board[:,np.newaxis] -> puts the axis in the second dimension [1,1,16]
board[:,:,np.newaxis] -> puts the axis in the third dimension [1,16,1]
import numpy as np
a = np.array([[4,4,4,4,4,4,4,4,4,4,4,4,0,0,0,0]])
print(a.reshape(1,16,1).shape)
# input arrray
In [41]: arr
Out[41]: array([[4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0]])
In [42]: arr.shape
Out[42]: (1, 16)
# insert a singleton dimension at the end
In [44]: arr_3D = np.expand_dims(arr, -1)
# desired shape
In [45]: arr_3D.shape
Out[45]: (1, 16, 1)
In [47]: arr[..., None]
In [48]: arr[..., np.newaxis]