nob*_*ody 32 python numpy multidimensional-array
我有一个带有形状(x,y)的二维数组,我想将其转换为具有形状(x,y,1)的3d数组.有没有一个很好的Pythonic方法来做到这一点?
Mar*_*son 55
除了其他答案,您还可以使用切片numpy.newaxis:
>>> from numpy import zeros, newaxis
>>> a = zeros((6, 8))
>>> a.shape
(6, 8)
>>> b = a[:, :, newaxis]
>>> b.shape
(6, 8, 1)
Run Code Online (Sandbox Code Playgroud)
甚至这个(它将使用任意数量的维度):
>>> b = a[..., newaxis]
>>> b.shape
(6, 8, 1)
Run Code Online (Sandbox Code Playgroud)
Win*_*ert 10
numpy.reshape(array, array.shape + (1,))
Run Code Online (Sandbox Code Playgroud)
小智 5
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
60030 次 |
| 最近记录: |