[Numpy-discussion] Casting a float array into a string array

Anne Archibald peridot.faceted@gmail....
Fri Oct 5 09:48:41 CDT 2007


On 05/10/2007, Matthieu Brucher <matthieu.brucher@gmail.com> wrote:
> I'd like to have the '2.', because if the number is negative, only '-' is
> returned, not the real value.

For string arrays you need to specify the length of the string as part
of the data type (and it defaults to length 1):

In [11]: random.normal(size=(2,3)).astype("|S20")
Out[11]:
array([['-0.223407464804', '1.1952765837', '-2.24073805089'],
       ['1.36604738338', '-0.197059880309', '2.15648625075']],
      dtype='|S20')

In [12]: random.normal(size=(2,3)).astype("|S2")
Out[12]:
array([['-0', '1.', '-0'],
       ['0.', '0.', '1.']],
      dtype='|S2')

In [13]: random.normal(size=(2,3)).astype("str")
Out[13]:
array([['-', '1', '1'],
       ['-', '-', '0']],
      dtype='|S1')

Anne


More information about the Numpy-discussion mailing list