1

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 ?

1
  • 1
    This is a too particular example. What would be the effect on an array like np.arange(16).reshape(4, 4)? Commented Aug 16, 2022 at 10:20

3 Answers 3

2

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]]
Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't really substract 1 from all the values, it just replace the last row with a new one.
1

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]]

3 Comments

This doesn't really substract 1 from all the values, it just replace the last row with a new one.
What the op asked was to make "all of the rows go one unit down". I assume that the row in the example were made sequential just to show that they are different and that the real array contains random numbers.
Yeah, this is kind of my point. Your solution ignores the actual values.
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.