ircham
ircham

Reputation: 129

2D array operation in python

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

Upvotes: 1

Views: 74

Answers (1)

yatu
yatu

Reputation: 88236

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)

Upvotes: 6

Related Questions