1

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,:]?

4

1 回答 1

5

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,:]

创建 的A[1,:]和 的视图A[0,:],然后将 的值分配A[0,:]为等于 的视图中的值A[1,:]。但是当它开始分配时A[1,:]A[0,:]的视图现在显示的是复制后的数据,所以你得到了不正确的结果。在这种情况下,只需.copy在此处添加第二个元素就足够了:

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

因为右边的元组总是在左边的赋值开始之前完全构建,所以你可以使用实时视图进行第一次赋值,只需要复制保存第二次赋值的值。

于 2017-12-30T02:06:57.023 回答