Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
633 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...