How to shift contents referenced by numpy array names in python

In python, I have numpy arrays a0, a1, and a2, each of which refer to different contents. I want to shift the relations between the reference names and the referred objects, so that a2 will now point to the content pointed by a1 before, and a1 will now point to the content pointed by a0 before. Then, I want to let a0 to point to a new content.

To be more specific, I want to do something like this:

import numpy as np
# I want to assign new values to a0[0], a0[1], .., without affecting a1. 

Can I do it without copying values (e.g. by np.copy) and without memory reallocation (e.g. by del and np.empty)?

2 answers

  • answered 2018-11-08 08:29 Albin Paul

    Use tuple unpacking to exchanging values kindaof like the a,b=b,a

    In [183]: a2=np.array([1,2,3,4])
         ...: a1=np.array([10,20,30,40])
         ...: a0=np.array([8,8,8,8]) 
    In [184]: 
    In [185]: a2,a1=np.copy(a1),np.copy(a0)
    In [186]: a0
    Out[186]: array([8, 8, 8, 8])
    In [187]: a1
    Out[187]: array([8, 8, 8, 8])
    In [188]: a2
    Out[188]: array([10, 20, 30, 40])

    You are free to point a0 where ever you want and i dont think you can create get away with changing a0 and not affecting a1 without np.copy or something else like copy.deepcopy

  • answered 2018-11-08 11:21 AndyK

    What are you asking is not possible without making a copy of a0, otherwise a0 and a1 will be pointing to the same object and changing a0 will change a1. So you should do this:

    a2 = np.array([1,2,3,4])
    a1 = np.array([10,20,30,40])
    a0 = np.array([8,8,8,8]) 
    a2 = a1
    a1 = a0.copy()
    # let's change a0
    a0[0] = 9
    # check
    Out[31]: array([9, 8, 8, 8])
    Out[32]: array([8, 8, 8, 8])
    Out[33]: array([10, 20, 30, 40])