[SciPy-User] determining types in dtype

Skipper Seabold jsseabold at gmail.com
Sun Mar 21 21:30:14 EDT 2010


2010/3/21 Ernest Adrogué <eadrogue at gmx.net>:
> 21/03/10 @ 13:14 (-0400), thus spake Skipper Seabold:
>> Is there an easy way to determine if the dtype of a (non-nested)
>> structured-array is homogenous/similar?  Basically, I want to know if
>> all elements are int and/or float so it can be safely cast to an
>> ndarray or if it contains strings (or, more generally, other objects)
>> so it needs some more processing.
>>
>> I thought issctype might provide what I'm looking for but
>>
>> import numpy as np
>> X = np.array([('1', 1.0), ('1', 1.0), ('1', 1.0)],
>>       dtype=[('foo', 'a1'), ('bar', '<f8')])
>> np.issctype(X.dtype)
>> # True
>>
>> Similar result for nested structs of string type
>>
>> Y = np.array([(('1','2'), 1.0), (('1','2'), 1.0), (('1','2'), 1.0)],
>>       dtype=[('foo', 'a1', (1,2)), ('bar', '<f8')])
>> np.issctype(Y.dtype)
>> # True
>>
>> In particular, I find this odd
>>
>> np.issctype(str)
>> # True
>>
>> I would expect this to be like
>>
>> np.issctype(object)
>> # False
>>
>> Unless there is something I don't understand about types, which is
>> probably the case.
>>
>> The only other way I can think of is to use X.dtype.descr and actually
>> parse the list to determine the types.  Any thoughts?
>
> Yes, this is what I do. From X.dtype.fields you get the dtype
> of each field:
>
> dtypes = set(i[0] for i in X.dtype.fields.values())
> if len(dtypes) == 1:
>        print 'homogenous'
>        view = X.view(dtypes.pop())
> else:
>        print 'heterogenous'
>

Thanks, I think I will take a similar approach.  np.can_cast also
looks very helpful.

Skipper



More information about the SciPy-User mailing list