[Numpy-discussion] making a character array from numeric array
oliphant at ee.byu.edu
Mon Mar 27 15:48:05 CST 2006
Michael Sorich wrote:
> 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:
fl = arr.flat
l = [str(x) for x in fl]
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)
More information about the Numpy-discussion