我有一个 3-D NumPy 数组,例如
a = np.random.random((2,3,5))
我想转置最后两个轴,即
b = a.transpose(0,2,1)
但是,我不想要一个步履蹒跚的观点!我想实际复制数组并在内存中重新排序。实现这一目标的最佳方法是什么?
The copy()
method will reorder to C-contiguous order by default:
b = a.transpose(0,2,1).copy()
Be careful: the copy()
function has a different default behavior. With the function, you must explicitly specify the order to ensure a C-contiguous copy:
b = np.copy(a.transpose(0,2,1), order='C')
(Note that the docstring for the function says that the ndarray method is the preferred method for creating an array copy.)
在引擎盖下,b 的步幅与 a 不同。
更喜欢使用ascontiguousarray,它会在需要时复制内存。而copy
将始终复制内存。