1

I have a 2D array, I want the element i of the array in every row to be reduced by element i-1 in the same row

I've tried this code:

data = np.arange(12).reshape(3,4)
print(data)
for row in data:
    for cell in row:
        data[cell] = data[cell]-data[cell-1]

print(data)

and i got an output like this

[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
Traceback (most recent call last):
  File "D:/testing/test.py", line 55, in <module>
    data[cell] = data[cell]-data[cell-1]

IndexError: index -8 is out of bounds for axis 0 with size 3

and i want output like this

[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

[[1 1 1]
 [1 1 1]
 [1 1 1]]

the main process was data[i] = data[i]-data[i-1]. i need this process for huge scale of data like more than 1024x1024 so i need something efficient

3
  • What do you want to do about the first element in a row? Commented Apr 7, 2020 at 13:12
  • @mrzo whatever, reduced by 0 or eliminated Commented Apr 7, 2020 at 13:14
  • Print row and cell inside the loops to better understand how they work. Commented Apr 7, 2020 at 14:18

1 Answer 1

6

You can slice both arrays and subtract:

data[:,1:] - data[:,:-1]

array([[1, 1, 1],
       [1, 1, 1],
       [1, 1, 1]])

Or taking the np.diff:

np.diff(data)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.