简体   繁体   English

Numpy:如何减去数组中的所有其他元素

[英]Numpy: How to subtract every other element in array

I have the following numpy array我有以下 numpy 数组

u = np.array([a1,b1,a2,b2...,an,bn])

where I would like to subtract the a and b elements from each other and end up with a numpy array:我想将 a 和 b 元素彼此相减,最终得到一个 numpy 数组:

u_result = np.array([(a2-a1),(b2-b1),(a3-a2),(b3-b2),....,(an-a_(n-1)),(an-a_(n-1))])

How can I do this without too much array splitting and for loops ?如何在没有太多数组拆分for 循环的情况下做到这一点? I'm using this in a larger loop so ideally, I would like to do this efficiently (and learn something new)我在一个更大的循环中使用它非常理想,我想有效地做到这一点(并学习新的东西)

(I hope the indexing of the resulting array is clear) (我希望结果数组的索引是清楚的)

Or simply, perform a substraction:或者简单地说,执行减法:

u = np.array([3, 2, 5, 3, 7, 8, 12, 28])
u[2:] - u[:-2]

Output: Output:

array([ 2,  1,  2,  5,  5, 20])

You can try in this way.你可以试试这种方式。 Firstly, split all a and b elements using array[::2], array[1::2] .首先,使用array[::2], array[1::2]拆分所有a and b元素。 Finally, subtract from b to a (np.array(array[1::2] - array[::2])) .最后,从b to a (np.array(array[1::2] - array[::2]))

import numpy as np

array = np.array([7,8,9,6,5,2])

u_result = np.array(array[1::2] - array[::2] )
print(u_result)

Looks like you need to use np.roll :看起来您需要使用np.roll

shift = 2
u = np.array([1, 11, 2, 12, 3, 13, 4, 14])
shifted_u = np.roll(u, -shift)
(shifted_u - u)[:-shift]

Returns:回报:

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

you can use ravel torearrange as your original vector.您可以使用 ravel torearrange 作为原始向量。

Short answer:简短的回答:

u_r = np.ravel([np.diff(u[::2]), 
                np.diff(u[1::2])], 'F')

Here a long and moore detailed explanation:这里有一个冗长而详细的解释:

  1. separate a from b in u this can be achieved indexingu中将ab分开,这可以实现索引
  2. differentiate a and b you can use np.diff for easiness of code.区分ab你可以使用 np.diff 来简化代码。
  3. ravel again the differentiated values.再次解开差异化的价值观。
#------- Create u---------------
import numpy as np

a_aux = np.array([50,49,47,43,39,34,28])
b_aux = np.array([1,2,3,4,5,6,7])

u = np.ravel([a_aux,b_aux],'F')
print(u)
#-------------------------------
#1)
# get a as elements with index 0, 2, 4 ....
a = u[::2]
b = u[1::2] #get b as 1,3,5,....
#2)
#differentiate
ad = np.diff(a)
bd = np.diff(b)
#3)
#ravel putting one of everyone
u_result = np.ravel([ad,bd],'F')

print(u_result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM