[Numpy-discussion] retrieving type objects for void array-scalar objects

Francesc Altet faltet at carabos.com
Sat Feb 4 01:34:02 CST 2006


El dv 03 de 02 del 2006 a les 22:05 +0100, en/na N. Volbers va escriure:
> >>> dtype = numpy.dtype({'names': ['name', 'weight'],'formats': ['U30', 'f4']})
> >>> a = numpy.array([(u'Bill', 71.2), (u'Fred', 94.3)], dtype=dtype)

> Is there some way to retrieve the type object directly from the array (not using any existing row) using only the name of the item?  I have checked the dtype attribute, but I could only get the character representation for the item types (e.g. 'f4').

To retrieve the type directly from the array, you can use a function
like this:

def get_field_type_flat(descr, fname):
    """Get the type associated with a field named `fname`.

    If the field name is not found, None is returned.
    """

    for item in descr:
	if fname == item[0]:
            return numpy.typeDict[item[1][1]]
    return None

That one is very simple and fast. However, it can't deal with nested
types. The next one is more general:

def get_field_type_nested(descr, fname):
    """Get the type associated with a field named `fname`.

    This funcion looks recursively in possible nested descriptions.
    If the field is not found anywhere in the hierarchy, None is
    returned.  If there are two names that are equal in the hierarchy,
    the first one (from top to bottom and from left to the right)
    found is returned.
    """

    for item in descr:
        descr = item[1]
	if fname == item[0]:
            return numpy.dtype(descr).type
        else:
            if isinstance(descr, list):
                return get_field_type(descr, fname)
    return None

The drawback here is that you can not select a field that is named the
same way and that lives in different levels of the hierarchy. For
example, selecting 'name' in a type structure like this:

+-----------+
|name |x    |
|     +-----+
|     |name |
+-----+-----+

is ambiguous (in the algorithm implemented above, the top level 'name'
would be selected). Addressing this problem would imply to define a way
to univocally specify nested fields.

Anyway, I'm attaching a file with several examples on these functions.

HTH,

-- 
>0,0<   Francesc Altet     http://www.carabos.com/
V   V   Cárabos Coop. V.   Enjoy Data
 "-"

-------------- next part --------------
A non-text attachment was scrubbed...
Name: prova.py
Type: text/x-python
Size: 1778 bytes
Desc: not available
Url : http://projects.scipy.org/pipermail/numpy-discussion/attachments/20060204/e079252c/attachment-0001.py 


More information about the Numpy-discussion mailing list