Search code examples
numpyvariable-assignmentnumpy-ndarraysub-arraynumpy-slicing

Numpy : How to assign directly a subarray from values when these values are step spaced


I have 2 global arrays "tab1" and "tab2" with dimensions respectively equal to 21x21 and 17x17.

I would like to assign the block of "tab1" ( indexed by [15:20,0:7]) by the block of "tab2" indexed by [7:17:2,0:7] (so with a step between elements of 1st array dimension) : I tried whith this syntax :

tab1[15:20,0:7] = tab2[7:17:2,0:7]

Unfortunately, this doesn't work, it seems that only "diagonal" (I mean one by one) elements of 15:20 are taken into account following the values of "tab2" along [7:17:2].

Is there a way to assign a subarray of "tab1" with another subarray "tab2" composed of indexes with step spaced values ?

If someone could see what's wrong or suggest another method, this would be nice.

UPDATE 1: indeed, from my last tests, it seems good but is it also the same for the assignment of block [15:20,15:20] :

tab1[15:20,15:20] = tab2[7:17:2,7:17:2]  

??

ANSWER : it seems ok also for this block assignment, sorry


Solution

  • The assignment works as I expect.

    In [1]: arr = np.ones((20,10),int)                                                             
    

    The two blocks have the same shape:

    In [2]: arr[15:20, 0:7].shape                                                                  
    Out[2]: (5, 7)
    In [3]: arr[7:17:2, 0:7].shape                                                                 
    Out[3]: (5, 7)
    

    and assigning something interesting, looks right:

    In [4]: arr2 = np.arange(200).reshape(20,10)                                                   
    In [5]: arr[15:20, 0:7] = arr2[7:17:2, 0:7]                                                    
    In [6]: arr                                                                                    
    Out[6]: 
    array([[  1,   1,   1,   1,   1,   1,   1,   1,   1,   1],        
            ...
           [  1,   1,   1,   1,   1,   1,   1,   1,   1,   1],
           [ 70,  71,  72,  73,  74,  75,  76,   1,   1,   1],
           [ 90,  91,  92,  93,  94,  95,  96,   1,   1,   1],
           [110, 111, 112, 113, 114, 115, 116,   1,   1,   1],
           [130, 131, 132, 133, 134, 135, 136,   1,   1,   1],
           [150, 151, 152, 153, 154, 155, 156,   1,   1,   1]])
    

    I see a (5,7) block of values from arr2, skipping rows like [80, 100,...]