Search code examples
pythonarraysnumpyin-place

Re-arranging numpy array in place


I am trying to modify a numpy array "in-place". I am interested in re-arranging the array in-place (instead of return:ing a re-arranged version of the array).

Here is an example code:

  from numpy import *

  def modar(arr):
    arr=arr[[1,0]] # comment & uncomment this line to get different behaviour
    arr[:,:]=0 
    print "greetings inside modar:"
    print arr

  def test2():
    arr=array([[4,5,6],[1,2,3]])
    print "array before modding"
    print arr
    print
    modar(arr)
    print
    print "array now"
    print arr

  test2()

The assignment ar=arr[[1,0]] breaks the correspondence of "arr" to the original array passed to the function "modar". You can confirm this by commenting/uncommenting that line.. this happens, of course, as a new array has to be created.

How can I tell python that the new array still corresponds to "arr"?

Simply, how can I make "modar" to rearrange the array "in-place"?

Ok.. I modified that code and replaced "modarr" by:

def modar(arr):
  # arr=arr[[1,0]] # comment & uncomment this line to get different behaviour
  # arr[:,:]=0 
  arr2=arr[[1,0]]
  arr=arr2
  print "greetings inside modar:"
  print arr

The routine "test2" still gets an unmodified array from "modar".


Solution

  • In this case you could do:

      arr2 = arr[[1, 0]]
      arr[...] = arr2[...]
    

    where the temporary array arr2 is used to store the fancy indexing result. The last line copies the data from arr2 to the original array, keeping the reference.

    Note: be sure in your operations that arr2 has the same shape of arr in order to avoid strange results...