[英]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)
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:这里有一个冗长而详细的解释:
a
from b
in u
this can be achieved indexingu
中将a
与b
分开,这可以实现索引a
and b
you can use np.diff for easiness of code.a
和b
你可以使用 np.diff 来简化代码。#------- 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.