[Numpy-discussion] Find the N maximum values and corresponding indexes in an array

Howard Chong hgchong@berkeley....
Thu Dec 3 11:24:44 CST 2009


Thanks for all the help and suggestions. I think the partial sort is exactly
what I need.

I thought of doing it as a full sort with argsort(), but that would be much
slower if I just need a small number (maybe 7) from a large array,
potentially thousands or a million repeated many times.

In case you are wondering, I am doing this to find the 7 nearest neighbors
in a GIS. For a list of zipcodes in America, find the 7 nearest weather
stations.


> Message: 8
> Date: Wed, 02 Dec 2009 22:26:29 -0500
> From: Neal Becker <ndbecker2@gmail.com>
> Subject: Re: [Numpy-discussion] Find the N maximum values and
>        corresponding   indexes in an array
> To: numpy-discussion@scipy.org
> Message-ID: <hf7b56$jam$1@ger.gmane.org>
> Content-Type: text/plain; charset="ISO-8859-1"
>
> Neal Becker wrote:
>
> > Keith Goodman wrote:
> > ...
> >> Oh, I thought he meant there was a numpy function for partial
> sorting.
> >>
> Try this one:
>
> template<typename in_t>
> inline void partial_sort (in_t in, int n_el) {
>  std::partial_sort (boost::begin (in), boost::begin(in) + n_el,
> boost::end (in));
> }
> ...
>  def ("partial_sort",
> &partial_sort<pyublas::numpy_
> strided_vector<int32_t> >);
>  def ("partial_sort",
> &partial_sort<pyublas::numpy_strided_vector<int64_t> >);
>  def ("partial_sort",
> &partial_sort<pyublas::numpy_strided_vector<double> >);
> ---------
> import pyublas
> import numpy as np
> u = np.arange (20)[::-1]
> from numpy_fncs import partial_sort
> partial_sort (u, 4)
> In [2]: u
> Out[2]:
> array([ 0,  1,  2,  3, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10,  9,  8,
> 7,
>        6,  5,  4])
>
>
> --
> Howard Chong
> Dept. of Agricultural and Resource Economics and Energy Institute @ Haas
> Business School
> UC Berkeley
> hgchong@berkeley.edu
> Cell: 510-333-0539
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/numpy-discussion/attachments/20091203/8da7abc9/attachment.html 


More information about the NumPy-Discussion mailing list