[Numpy-discussion] convert to string - astype(str)

josef.pktd@gmai... josef.pktd@gmai...
Sat Jun 9 16:45:41 CDT 2012


Is there a way to convert an array to string elements in numpy,
without knowing the string length?


>>> arr2 = np.arange(8, 13)

>>> arr2.astype(str)   # bad
array(['8', '9', '1', '1', '1'],
      dtype='|S1')

>>> arr2.astype('S2')
array(['8', '9', '10', '11', '12'],
      dtype='|S2')

>>> map(str, arr2)
['8', '9', '10', '11', '12']


>>> arr3 = np.round(np.random.rand(5), 2)
>>> arr3
array([ 0.51,  0.86,  0.15,  0.68,  0.59])

>>> arr3.astype(str)   # bad
array(['0', '0', '0', '0', '0'],
      dtype='|S1')

>>> arr3.astype('S4')
array(['0.51', '0.86', '0.15', '0.68', '0.59'],
      dtype='|S4')

>>> map(str, arr3)
['0.51', '0.86', '0.15', '0.68', '0.59']

>>> np.__version__
'1.5.1'

(from an issue in statsmodels)

Thanks,

Josef


More information about the NumPy-Discussion mailing list