Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Row exchange in Numpy [duplicate]

Tags:

In Python I can exchange 2 variables by mean of multiple affectation; it works also with lists:

l1,l2=[1,2,3],[4,5,6] l1,l2=l2,l1 print(l1,l2) >>> [4, 5, 6] [1, 2, 3] 

But when I want to exchange 2 rows of a numpy array (for example in the Gauss algorithm), it fails:

import numpy as np a3=np.array([[1,2,3],[4,5,6]]) print(a3) a3[0,:],a3[1,:]=a3[1,:],a3[0,:] print(a3) >>> [[1 2 3]      [4 5 6]]     [[4 5 6]      [4 5 6]] 

I thought that, for a strange reason, the two columns were now pointing to the same values; but it's not the case, since a3[0,0]=5 after the preceeding lines changes a3[0,0] but not a3[1,0].

I have found how to do with this problem: for example a3[0,:],a3[1,:]=a3[1,:].copy(),a3[0,:].copy() works. But can anyone explain why exchange with multiple affectation fails with numpy rows? My questions concerns the underlying work of Python and Numpy.

like image 643
JPG Avatar asked Jan 22 '14 16:01

JPG


People also ask

How do I swap columns and rows in NumPy array?

To transpose NumPy array ndarray (swap rows and columns), use the T attribute ( . T ), the ndarray method transpose() and the numpy. transpose() function.

How do you swap two rows in a matrix?

So, to swap two rows of a matrix, left-multiply it by the appropriately-sized idenity matrix that has had its corresponding rows swapped. For example, to swap rows 0 and 2 of a 3×n matrix, left-multiply it by [001010100].


1 Answers

This works the way you intend it to:

a3[[0,1]] = a3[[1,0]] 

The two separate assignments in the tuple assignment are not buffered with respect to eachother; one happens after the other, leading the overwriting your observe

like image 105
Eelco Hoogendoorn Avatar answered Sep 20 '22 06:09

Eelco Hoogendoorn