从numpy中的下一行第一个元素中减去第二个元素的当前行

时间:2022-12-28 19:36:19

I have 6x2 numpy array. I want to subtract current rows second element from the next rows first element and get the new column. Currently i'm using for loop to do that. Ex:

我有6x2 numpy数组。我想从下一行第一个元素中减去第二个元素的当前行并获取新列。目前我正在使用for循环来做到这一点。例如:

from numpy import array
a = array([[1,3],
           [2,5],
           [6,7],
           [8,9],
           [5,6],
           [6,9]])
k = []
for i in range(a.shape[0]-1):
    k.append(a[i][1]-a[i+1][0])
array(k)

Output : [1, -1, -1, 4, 0]

输出:[1,-1,-1,4,0​​]

How can I get the same output using numpy?

如何使用numpy获得相同的输出?

1 个解决方案

#1


1  

Slice and subtract -

切片和减法 -

a[1:,0] - a[:-1,1]

Sample run -

样品运行 -

In [303]: a
Out[303]: 
array([[1, 3],
       [2, 5],
       [6, 7],
       [8, 9],
       [5, 6],
       [6, 9]])

In [304]: a[1:,0] - a[:-1,1]
Out[304]: array([-1,  1,  1, -4,  0])

Since, we have two columns only, another way/trick would be to use differentiaton on flattened version and then step into every other element starting from the second element -

因为,我们只有两列,另一种方法/技巧是在扁平版本上使用差分,然后从第二个元素开始逐步进入每个其他元素 -

In [308]: np.diff(a.ravel())[1::2]
Out[308]: array([-1,  1,  1, -4,  0])

#1


1  

Slice and subtract -

切片和减法 -

a[1:,0] - a[:-1,1]

Sample run -

样品运行 -

In [303]: a
Out[303]: 
array([[1, 3],
       [2, 5],
       [6, 7],
       [8, 9],
       [5, 6],
       [6, 9]])

In [304]: a[1:,0] - a[:-1,1]
Out[304]: array([-1,  1,  1, -4,  0])

Since, we have two columns only, another way/trick would be to use differentiaton on flattened version and then step into every other element starting from the second element -

因为,我们只有两列,另一种方法/技巧是在扁平版本上使用差分,然后从第二个元素开始逐步进入每个其他元素 -

In [308]: np.diff(a.ravel())[1::2]
Out[308]: array([-1,  1,  1, -4,  0])