Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

question about numpy 1-D array 1

Status
Not open for further replies.

VickyC

Technical User
Sep 25, 2010
206
CA
Consider a numpy array like this...

a = array([1, 7, 2, 8, 1, 2, 3, 8, 5])

Some of the array elements appear just once (ie 3, 5, and 7), but we are interested in the array elements that appear twice (ie 1, 2, and 8).

I need to find the GAP (index difference) between identical elements.

In the example...

Code:
element  gap
--------------
   1      4
   2      3
   8      4

Any help is greatly appreciated
Vicky C.

 
You can create a dictionary with the index as the key and your list value as the value; in your example:
[tt](0:1,1:7,2:2,3:8,...)[/tt]
Then you sort the hash by value, and iterate through it to determine the index (key) difference of adjacent couples. You should also define what to do if you find triplets or more.
Another way is to use two nested loops using indices [tt]i,j[/tt]: the outer one iterates with [tt]i[/tt] over the whole array, the inner loop iterates over the same array starting with [tt]j=i+1[/tt].
Don't know which one would be faster, likely the second one.

: Online engineering calculations
: Magnetic brakes for fun rides
: Air bearing pads
 
hi prex1
Thanks for those two good ideas.
I'm guessing it should also be possible to use the numpy.where, but I haven't been successful yet (ie: iterating through the array values to determine the indices of each value. That could be the fastest of all.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top