[Numpy-discussion] Slices of structured arrays
Robert Ferrell
ferrell@diablotech....
Mon Jun 1 18:09:15 CDT 2009
On Jun 1, 2009, at 4:41 PM, Robert Kern wrote:
> On Mon, Jun 1, 2009 at 17:32, Robert Ferrell
> <ferrell@diablotech.com> wrote:
>> Is there a way to get slices of a structured array and keep the field
>> names? For instance, I've got dtype=[('x','f4'),('y','f4'),
>> ('z','f4')] and I want to get just the x & y slices into a new array
>> with dtype=[('x','f4'),('y','f4')].
>>
>> I can just make a new dtype, and extract what I need, but I'm
>> wondering if there's some simple way to do this that I haven't found.
>>
>> Here's what I know works:
>>
>> # Make a len 10 array with 3 fields, 'x', 'y', 'z'
>> In [647]: xyz = np.array(zip(*np.random.random_integers(low=10,
>> size=(3,10))), dtype=[('x', 'f4'), ('y', 'f4'), ('z', 'f4')])
>>
>> # Get just the 'x' and 'y' fields
>> In [648]: xy = np.array( zip(xyz['x'], xyz['y'] ), dtype=[('x','f4'),
>> ('y', 'f4')])
>>
>> In [649]: xyz['x']
>> Out[649]: array([ 4., 1., 1., 5., 1., 2., 9., 8., 1., 9.],
>> dtype=float32)
>>
>> In [650]: xy['x']
>> Out[650]: array([ 4., 1., 1., 5., 1., 2., 9., 8., 1., 9.],
>> dtype=float32)
>>
>> That works, but just feels like there's probably an elegant
>> solution I
>> don't know. I couldn't find anything in the docs, but I may not have
>> been using the right search words.
>
> In numpy 1.4, there will be a function that does this,
> numpy.lib.recfunctions.drop_fields(). In the meantime, you can
> copy-and-paste it into your own code:
>
> http://svn.scipy.org/svn/numpy/trunk/numpy/lib/recfunctions.py
>
> Or use it from it's original source,
> matplotlib.mlab.rec_drop_fields(), if you have matplotlib.
That's perfect. I've got matplotlib, so I'll use that for now.
thanks,
-robert
More information about the Numpy-discussion
mailing list