[Numpy-discussion] Numpify this?

Matt Crane matt@snapbug.geek...
Sun May 18 02:04:29 CDT 2008


Hey,

I'm new to numpy but not new to python or programming in general. I
was wondering if there's a way of using numpy to do the following or
whether I've got what I've got and that's as good as it's going to
get.

I have two 2d arrays and I want to create another 2d array that
contains the values from the 2nd column of the first two arrays where
the values in the 1st column match. To elaborate with an example - if
I had an array a:

array([[2834, 1], [3282, 3], [6850, 2], [9458, 2]])
and an array b:

array([[2834, 3], [3282, 5], [4444, 5], [9458, 3], [9999, 4], [11111,
5], [12345, 1]])

then I'd want the result to be

array([[1, 3],   # from 2834
       [3, 5],    # from 3282
       [2, 3]])   # from 9458

This is what I have at the moment:

results = []
while aind < amax and bind < bmax:
    if a[aind, 0] < b[bind, 0]:
            aind += 1
    elif a[aind, 0] > b[bind, 0]:
            bind += 1
    else:
            results.append([a[aind, 1], b[bind, 1]])
            aind += 1
            bind += 1
results = array(results)

Where aind = bind = 0, amax = a.shape[0] and bmax = b.shape[0].

Any tips/pointers/speedups?

Cheers,
Matt


More information about the Numpy-discussion mailing list