Home > Blockchain >  shift a row in a numpy array
shift a row in a numpy array

Time:08-16

I have a numpy array like this :

[[1,1,1,1,1],
 [2,2,2,2,2],
 [3,3,3,3,3],
 [4,4,4,4,4]]

and I need a function that make all of the rows go one unit down like this every time I implement it on my array :

[[0,0,0,0,0],
 [1,1,1,1,1],
 [2,2,2,2,2],
 [3,3,3,3,3]]

and for example for the next time of using it :

[[0,0,0,0,0],
 [0,0,0,0,0],
 [1,1,1,1,1],
 [2,2,2,2,2]]

is there any pre defined function which I could use or any trick code for my problem ?

CodePudding user response:

try rolling and replacing...

import numpy as np
def rollrep(arr):
    arr = np.roll(arr,axis=0, shift=1)
    arr[0,:] = 0
    return arr 

myarr = np.array([[1,1,1,1,1],
 [2,2,2,2,2],
 [3,3,3,3,3],
 [4,4,4,4,4]])

print(rollrep(myarr))

the output is

[[0 0 0 0 0]
 [1 1 1 1 1]
 [2 2 2 2 2]
 [3 3 3 3 3]]

CodePudding user response:

I would use slicing :

import numpy as np

arr = np.array([[1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [4, 4, 4, 4, 4]])
arr = np.append([[0,0,0,0,0]], arr[:-1], axis=0)
print(arr)

Output

[[0 0 0 0 0]
 [1 1 1 1 1]
 [2 2 2 2 2]
 [3 3 3 3 3]]

CodePudding user response:

You can use broadcasting to remove 1 everywhere and masking to only remove were the values of the array are positive. Here is the logic,

arr_shape = arr.shape
out = (arr[arr > 0] - 1).reshape(arr_shape)

if the shapes don't match, you can just jump to the next points.

For example, here out would be:

array([[0, 0, 0, 0, 0],
       [1, 1, 1, 1, 1],
       [2, 2, 2, 2, 2],
       [3, 3, 3, 3, 3]])

Doing that a second time (or more times), you will want to overwrite the slice of the array,

out[out > 0] = (out[out > 0] - 1)

Now out is:

array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [1, 1, 1, 1, 1],
       [2, 2, 2, 2, 2]])

N.B: You could just overwrite the slice from the beginning but depending on what you do with the arrays, you might want to keep the original array unchanged. If you don't care about the original array, you can just do:

arr[arr > 0] -= 1 # as many times as you want
  • Related