Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there any way to determine if an numpy array is record/structure array?

I cannot find any way to determine if an array is record array or not:

>>> import numpy as npy
>>> c0=npy.array([1,2])
>>> c=c0.view(dtype=[('x',int),('y',int)])
>>> c
array([(1, 2)], 
      dtype=[('x', '<i8'), ('y', '<i8')])

the type is always numpy.ndarray

>>> type(c)
<type 'numpy.ndarray'>
>>> isinstance(c,npy.recarray)
False

the element type is always numpy.void

>>> type(c[0])
<type 'numpy.void'>

now I use dtype.fields to determine it:

>>> def isRecarray(a):
    return a.dtype.fields != None

>>> isRecarray(c0)
False
>>> isRecarray(c)
True

Is there any official way to determine if an array is record array?

like image 828
Wang Avatar asked Jul 17 '14 22:07

Wang


2 Answers

Neither of those are record arrays. Per the docs:

>>> x = np.array([(1.0, 2), (3.0, 4)], dtype=[('x', float), ('y', int)])
>>> y = x.view(np.recarray)
>>> type(x), type(y)
(<type 'numpy.ndarray'>, <class 'numpy.core.records.recarray'>)

ndarray.view creates a new reference to the same memory, and as you call it also names the fields. There isn't a fundamental type difference between your c0 and c, they're both ndarrays.

like image 170
metaperture Avatar answered Oct 23 '22 22:10

metaperture


Since metaperture's answer explained how to distinguish whether a numpy array is record array but not a structured array, here's what I found in the docs:

Both the names and fields attributes will equal None for unstructured arrays. The recommended way to test if a dtype is structured is with if dt.names is not None rather than if dt.names, to account for dtypes with 0 fields.

So in your example,

>> import numpy as npy
>> c0=npy.array([1,2])
>> c=c0.view(dtype=[('x',int),('y',int)])
>> c
array([(1, 2)], dtype=[('x', '<i8'), ('y', '<i8')])

you are correct that

>> type(c) == type(c0)
True

but

>> c0.dtype.names
>> c0.dtype.names is None
True
>> c.dtype.names
('x', 'y')
>> c.dtype.names is None
False

allows you to see that c is a structured array while c0 is not! This is also true of np.recarray types, but I haven't played around with those too much.

like image 33
esg Avatar answered Oct 23 '22 23:10

esg