【发布时间】:2021-10-14 22:04:06
【问题描述】:
我有以下 numpy 数组:
import numpy as np
np.ones((10, 3, 2))
并且我需要将其重塑为<10,1,3,2>。
我该怎么做?
【问题讨论】:
标签: python arrays numpy reshape
我有以下 numpy 数组:
import numpy as np
np.ones((10, 3, 2))
并且我需要将其重塑为<10,1,3,2>。
我该怎么做?
【问题讨论】:
标签: python arrays numpy reshape
这个怎么样:
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
【讨论】: