0

I have two lists or arrays of uneven length (let's say arr_a, arr_b). I want to form a third array/list of tuples where the first element of the tuple take the value of arr_a[1st element] - arr_b[1st element] and the second element of the tuple taking arr_a[1st element] - arr_b[2nd element] and then the next tuple taking (arr_a[2nd_element]-arr_b[2nd_element], arr_a[2nd_element] - arr_b[3rd_element]) and so on. The code below achieves this using a for loop. But I want to find out if this can be achieved through some sort NumPy vectorizing, broadcasting approach. please note arr_a and arr_b are of not equal length ( len(arr_b) = len(arr_a)+1)

arr_a = np.random.randint(low = 0,high = 10,size = 10)
arr_b = np.random.randint(low = 0,high = 10,size = 11)

out:
arr_a : [4 8 6 3 3 7 8 6 0 2]
arr_b : [8 8 9 6 1 6 1 5 8 3 1]

list_c = []
for i,j in zip(range(len(arr_a)),range(len(arr_b))):
    list_c.append((arr_a[i]-arr_b[i],arr_a[i]-arr_b[i+1]))

out:
list_c : [(-4, -4), (0, -1), (-3, 0), (-3, 2), (2, -3), (1, 6), (7, 3), (1, -2), (-8, -3), (-1, 1)]
2
  • Numpy isnt going to help if you want tuples Commented Feb 8, 2020 at 6:21
  • I don't mind nested lists or arrays Commented Feb 8, 2020 at 6:23

2 Answers 2

2

I think you can try zip with numpy:

>>> list(zip(arr_a - arr_b[:-1], arr_a - arr_b[1:]))
[(-4, -4),
 (0, -1),
 (-3, 0),
 (-3, 2),
 (2, -3),
 (1, 6),
 (7, 3),
 (1, -2),
 (-8, -3),
 (-1, 1)]
Sign up to request clarification or add additional context in comments.

Comments

2

In order to keep the data in two columns rather than a tuple (which does not play well with numpy given that the data would be an object rather than a numeric dtype):

>>> (arr_a - np.array([arr_b[:-1], arr_b[1:]])).T
array([[-4, -4],
       [ 0, -1],
       [-3,  0],
       [-3,  2],
       [ 2, -3],
       [ 1,  6],
       [ 7,  3],
       [ 1, -2],
       [-8, -3],
       [-1,  1]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.