How to subtract the previous rows column from current column and create a new dimension in the array with this value using numpy?

What I want to do is take my current array and subtract the previous rows column value from the current rows column value. I also want to take the result and add it to the array as a new dimension.

Example Array:

[[1,2,4,7,9,15], [3, 4,3,5,10,2], [5,6,56,7,20,1]]

Lets say I want to do this with the 4th column so I want the output to be an array that looks like this:

[[1,2,4,7,9,15,0], [3, 4,3,5,10,2,-2], [5,6,56,7,20,1,2]]

Thanks

Answers


You can do this using a combination of np.diff, and concatenate options, like so:

import numpy as np
myarray = np.array([[1,2,4,7,9,15], [3, 4,3,5,10,2], [5,6,56,7,20,1]])
#your differences appears to be wraparound, so we repeat the last row at the top:
myarray_wrap = np.vstack((myarray[-1],myarray))
#this gets the diffs for all columns:
column_diffs = np.diff(myarray_wrap, axis=0)
#now we add in only the the column_diff that we want, at the end:
print np.hstack((myarray, column_diffs[:,3].reshape(-1,1)))
#Output:
[[ 1  2  4  7  9 15  0]
 [ 3  4  3  5 10  2 -2]
 [ 5  6 56  7 20  1  2]]

This Python code should solve your problem.

previous = None
for row in rows:
 current = row[4]
 row.append( 0 if previous == None else current - previous )
 previous = current

Need Your Help

Program data folders in Linux

linux ubuntu directory organization application-data

This is a more general and noob question. I am developing a small application in Linux (Ubuntu, to be more precise) and at this point I have an executable, a shared library (.so), a configuration f...