python assignment in array vs scalar

こ雲淡風輕ζ 提交于 2019-12-02 07:11:52

问题


I have a 2D array A of shape (4,3), and a 1D array a of shape (4,). I want to swap the first two rows of A, as well as the first two elements in a. I did the following:

A[0,:],A[1,:] = A[1,:],A[0,:]
a[0],a[1] = a[1],a[0]

Apparently, it works for a, but fails for A. Now, the second row becomes the first row, but the first row remains unchanged. If I do the following:

first_row_copy = A[0,:].copy()
A[0,:] = A[1,:]
A[1,:] = first_row_copy

Then, it seems to work. Why the first method doesn't work? (but works for a) Also, what's the difference between A_copy = A[0,:].copy() and A_copy = A[0,:]?


回答1:


numpy slices are views of the underlying memory, they don't make independent copies by default (this is a performance/memory optimization). So:

A[0,:],A[1,:] = A[1,:],A[0,:]

Makes a view of A[1,:] and a view of A[0,:], then assigns the values of A[0,:] to equal what's in the view of A[1,:]. But when it gets to assigning A[1,:], A[0,:]'s view is now showing the post-copy data, so you get the incorrect result. Simply adding .copy to the second element here would be sufficient in this case:

A[0,:], A[1,:] = A[1,:], A[0,:].copy()

because the tuple on the right is always constructed completely before assignments to the left begin, so you can use the live view for the first assignment, and only need to make a copy to preserve the values for the second assignment.



来源:https://stackoverflow.com/questions/48030280/python-assignment-in-array-vs-scalar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!