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

josef.pktd at gmail.com josef.pktd at gmail.com
Sat Jun 9 17:45:41 EDT 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