1

我想要做的是获取我当前的数组并从当前行列值中减去前一行列值。我还想获取结果并将其作为新维度添加到数组中。

示例数组:

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

假设我想对第 4 列执行此操作,因此我希望输出是一个如下所示的数组:

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

谢谢

4

2 回答 2

1

您可以使用np.diff, 和concatenate选项的组合来执行此操作,如下所示:

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]]
于 2012-07-02T15:46:35.210 回答
0

这个 Python 代码应该可以解决您的问题。

previous = None
for row in rows:
 current = row[4]
 row.append( 0 if previous == None else current - previous )
 previous = current
于 2012-07-02T15:27:15.600 回答