问题
I have a 3-D NumPy array, e.g.
a = np.random.random((2,3,5))
I would like to transpose the last two axes, i.e.
b = a.transpose(0,2,1)
However, I do not want a view with twiddled strides! I want to actually copy the array and reorder it in memory. What is the best way to achieve this?
回答1:
The copy()
method will reorder to C-contiguous order by default:
b = a.transpose(0,2,1).copy()
回答2:
Under the hood, the stride of b is different than a.
prefer to use ascontiguousarray, which will copy the memory when it's needed. Whereas copy
will always copy memory.
来源:https://stackoverflow.com/questions/19826262/transpose-array-and-actually-reorder-memory