[Numpy-discussion] Converting char array to float

Travis E. Oliphant oliphant@enthought....
Wed Nov 28 18:05:33 CST 2007

Sameer DCosta wrote:
> I'm trying to convert a character array to a floating point array. I'm
> using one of the recent svn builds. It is surprising that astype does
> not do the job. However if I first convert the char array to an array
> and then use astype everything works fine. Is this a bug?
> import numpy as N
> print N.__version__  # Output = '1.0.5.dev4426'
> a = N.char.array(['123.45', '234.56'])
> b = N.array(a).astype(N.float)  # This works.
> print b
> b = a.astype(N.float)   # This does not work and raises an exception
> ValueError: Can only create a chararray from string data.

The problem is that astype for a chararray will by default try to create 
a class of chararray.  This sub-class only allows string data and so the 
base-class astype(float) will fail.

The astype method could be over-ridden in order to support automatic 
conversion to other kinds of arrays, but I lean towards asking "why?" 
because "explicit is better than implicit" (although it is admittedly 
arguable which is which in this case...)


> Thanks.
> Sameer
> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion@scipy.org
> http://projects.scipy.org/mailman/listinfo/numpy-discussion

More information about the Numpy-discussion mailing list