Tiger1
Tiger1

Reputation: 1377

How to calculate the inner distance of an array

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.

Upvotes: 0

Views: 111

Answers (3)

Christian Aichinger
Christian Aichinger

Reputation: 7227

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:]

Upvotes: 1

user2357112
user2357112

Reputation: 280227

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.

Upvotes: 2

HYRY
HYRY

Reputation: 97261

import numpy as np

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

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

Upvotes: 1

Related Questions