0

I'm trying to workout the distance between the inner values of two consecutive items in an array.

For examples:

>>> _array=[(5, 10), (15, 20), (25, 30), (35, 40)]
>>> np_array=[np.array(x) for x in _array]
>>> distance=[x - np_array[i - 1] for i, x in enumerate(np_array)][1:]
>>> distance
[array([10, 10]), array([10, 10]), array([10, 10])]

The example above calculates the distance between the items. What I'm really after is the distance between the inner attributes of any two consecutive items in the array i.e

(15-10),(25-20),(35-30)

Desired output: [(5),(5),(5)]

Any suggestions on how to go about this? Thanks.

3 Answers 3

2

First, because using non-NumPy datastructures with NumPy defeats the whole point:

_array = numpy.asarray(_array)

Then, just slice and subtract:

distances = array[1:, 0] - array[:-1, 1]

array[1:, 0] gets the first coordinate of all points after the first, array[:-1, 1] gets the second coordinate of all points before the last, and the subtraction is applied elementwise.

Sign up to request clarification or add additional context in comments.

Comments

1
import numpy as np

a = np.array([(5, 10), (15, 20), (25, 30), (35, 40)])

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

Comments

1

Simply access the index [0] for the current tuple and [1] for the previous one:

distance = [x[0] - np_array[i - 1][1] for i, x in enumerate(np_array)][1:]

2 Comments

While this works, if the OP is using NumPy, doing things with loops and list comprehensions defeats almost every benefit of NumPy.
@user2357112, thank you very much for the insight. I really want to take advantage of the benefit from numpy speed.

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.