On 05/27/2010 10:40 AM, Vincent Davis wrote:
On Thu, May 27, 2010 at 8:39 AM, Keith Goodman wrote:
To see if it is a number could you use something like:

np.issubdtype(a.dtype, float) or np.issubdtype(a.dtype, int) or
np.issubdtype(a.dtype, complex)

And for string:

np.issubdtype(a.dtype, str)

These are valid but what I don't like is that I need to know the list of possible number types. Basically I don't like a test that fails because I didn't know about a dtype. For string It is ok, the universe of is either string or not string. Maybe this is as good as it gets.

I guess my use case is that I want to be sure I can perform math on the values. So maybe I should just do someting like "numpy.lib._iotools._is_string_like" but "_is_number_like", Maybe there is such and I missed it. If not there should be.

Vincent

Can you give an example of what you are trying to do?

If some of your string arrays only have string representations of numbers that you want to do the math on then you have to attempt to convert those arrays into a numeric dtype (probably float) using for example asarray().

Bruce

>>> import numpy as np
>>> a=np.array([1,2,3])
>>> c=np.array(['1','2','3'])
>>> d=np.array(['a','b','1'])
>>> np.asarray(a, dtype=float)
array([ 1.,  2.,  3.])
>>> np.asarray(c,dtype=float)
array([ 1.,  2.,  3.])
>>> np.asarray(d,dtype=float)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.6/site-packages/numpy/core/numeric.py", line 284, in asarray
return array(a, dtype, copy=False, order=order)
ValueError: invalid literal for float(): a
>>> try:
...     np.asarray(d,dtype=float)
... except:
...     print 'fail'
...
fail