[Numpy-discussion] Suppressing "nesting" (recursion, descent) in array construction.
Francesc Altet
faltet at carabos.com
Wed Jun 20 07:57:42 EDT 2007
El dc 20 de 06 del 2007 a les 01:38 -0700, en/na Michael McNeil Forbes
va escriure:
> Hi,
>
> I have a list of tuples that I am using as keys and I would like to
> sort this along with some other arrays using argsort. How can I do
> this? I would like to do something like:
>
> # These are constructed using lists because they accumulate using
> append()
> data = [1.0, 3,0]
> keys = [('a',1),('b',2)]
>
> # Convert to arrays for indexing
> data = array(data1)
> keys = array(keys) # <--Converts to a 2d array rather than 1d array
> of tuples .
>
> inds = argsort(data)
> data[:] = data[inds]
> keys[:] = keys[inds]
>
> It seems there should be some way of specifying to the array
> constructor not to 'descend' (perhaps by specifying the desired
> dimensions of the final array or something) but I cannot find a nice
> way around this.
Here is a possible approach using recarrays:
In [54]:data = [3.0, 1.0]
In [55]:keys = [('a',1),('b',2)]
In [56]:tmp=numpy.array(keys, dtype="S1,i4")
In [57]:dest=numpy.empty(shape=len(keys), dtype="S1,i4,f8")
In [58]:dest['f0'] = tmp['f0']
In [59]:dest['f1'] = tmp['f1']
In [60]:dest['f2'] = data
In [61]:dest
Out[61]:
array([('a', 1, 3.0), ('b', 2, 1.0)],
dtype=[('f0', '|S1'), ('f1', '<i4'), ('f2', '<f8')])
In [62]:dest.sort(order='f2')
In [63]:dest
Out[63]:
array([('b', 2, 1.0), ('a', 1, 3.0)],
dtype=[('f0', '|S1'), ('f1', '<i4'), ('f2', '<f8')])
If you want to retrieve the keys and data from the dest recarray
afterwards, that's easy:
In [111]:data2=dest['f2'].tolist()
In [112]:keys2=dest.getfield('S1,i4').tolist()
In [113]:data2
Out[113]:[1.0, 3.0]
In [114]:keys2
Out[114]:[('b', 2), ('a', 1)]
Cheers,
--
Francesc Altet | Be careful about using the following code --
Carabos Coop. V. | I've only proven that it works,
www.carabos.com | I haven't tested it. -- Donald Knuth
More information about the NumPy-Discussion
mailing list