如何将 3D numpy 数组 <10,3,2> 重塑为 4D 数组 <10,1,3,2>?
How to reshape 3D numpy array <10,3,2> to 4D array <10,1,3,2>?
我有以下 numpy 数组:
import numpy as np
np.ones((10, 3, 2))
我需要将其重塑为 <10,1,3,2>
。
我该怎么做?
这个怎么样:
np.ones((10, 3, 2)).reshape([10,1,3,2])
x = np.ones((10, 3, 2))
# in place
x.shape = (10,1,3,2)
# new view
x.reshape((10,1,3,2))
# Add new axis
x[:, np.newaxis, :, :]
像其他人提到的那样,您可以 .reshape
它。另一种方法是像这样使用 np.newaxis
或 np.expand_dims
:
arr = np.ones((10, 3, 2))
arr1 = arr[:, np.newaxis, ...]
print(arr1.shape) # (10, 1, 3, 2)
arr2 = np.expand_dims(arr, 1)
print(arr2.shape) # (10, 1, 3, 2)
# check if the two arrays are equal
print(np.array_equal(arr1, arr2)) # True
我有以下 numpy 数组:
import numpy as np
np.ones((10, 3, 2))
我需要将其重塑为 <10,1,3,2>
。
我该怎么做?
这个怎么样:
np.ones((10, 3, 2)).reshape([10,1,3,2])
x = np.ones((10, 3, 2))
# in place
x.shape = (10,1,3,2)
# new view
x.reshape((10,1,3,2))
# Add new axis
x[:, np.newaxis, :, :]
像其他人提到的那样,您可以 .reshape
它。另一种方法是像这样使用 np.newaxis
或 np.expand_dims
:
arr = np.ones((10, 3, 2))
arr1 = arr[:, np.newaxis, ...]
print(arr1.shape) # (10, 1, 3, 2)
arr2 = np.expand_dims(arr, 1)
print(arr2.shape) # (10, 1, 3, 2)
# check if the two arrays are equal
print(np.array_equal(arr1, arr2)) # True