[Numpy-discussion] making a character array from numeric array

Travis Oliphant oliphant at ee.byu.edu
Mon Mar 27 15:48:05 CST 2006


Michael Sorich wrote:

> Hi,
>
> I am trying to convert an int or float ndarray into a string ndarray. 
> Using astype this is possible, but only if you explicity set the 
> number of characters (see eg below). It would be nice if just setting 
> type='S' (or N.str_) would automatically make an a character array of 
> sufficient size to hold the string representation. Is there a way to 
> do this?

Not with astype directly because to do what you want requires doing the 
conversion into variable-length strings and then finding the largest.    
But, you could do it this way:

def convert_to_string(arr):
       fl = arr.flat
       l = [str(x) for x in fl]
       return array(l).reshape(arr.shape)

Or as a one-liner

array([str(x) for x in arr.flat], dtype='S').reshape(arr.shape)

(The dtype='S' is technically unnecessary but should be a bit faster)

-Travis





More information about the Numpy-discussion mailing list