Dave31415 Dave31415 - 1 year ago 103
Python Question

Converting int arrays to string arrays in numpy without truncation

Trying to convert int arrays to string arrays in numpy

In [66]: a=array([0,33,4444522])
In [67]: a.astype(str)
array(['0', '3', '4'],

Not what I intended

In [68]: a.astype('S10')
array(['0', '33', '4444522'],

This works but I had to know 10 was big enough to hold my longest string. Is there a way of doing this easily without knowing ahead of time what size string you need? It seems a little dangerous that it just quietly truncates your string without throwing an error.

Answer Source

Again, this can be solved in pure Python:

>>> map(str, [0,33,4444522])
['0', '33', '4444522']

Or if you need to convert back and forth:

>>> a = np.array([0,33,4444522])
>>> np.array(map(str, a))
array(['0', '33', '4444522'], 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download