Home > Back-end >  Numpy: How to subtract every other element in array
Numpy: How to subtract every other element in array

Time:12-10

I have the following numpy array

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:

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? 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)

CodePudding user response:

Or simply, perform a substraction :

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

Output:

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

CodePudding user response:

you can use ravel torearrange as your original vector.

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 indexing
  2. differentiate a and b you can use np.diff for easiness of code.
  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)

CodePudding user response:

You can try in this way. Firstly, split all a and b elements using array[::2], array[1::2]. Finally, subtract from 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)

CodePudding user response:

Looks like you need to use 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])
  • Related