Converting int arrays to string arrays in numpy without truncation

前端 未结 5 1485
野的像风
野的像风 2020-12-08 02:31

Trying to convert int arrays to string arrays in numpy

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


        
5条回答
  •  爱一瞬间的悲伤
    2020-12-08 03:15

    You can find the smallest sufficient width like so:

    In [3]: max(len(str(x)) for x in [0,33,4444522])
    Out[3]: 7
    

    Alternatively, just construct the ndarray from a list of strings:

    In [7]: np.array([str(x) for x in [0,33,4444522]])
    Out[7]: 
    array(['0', '33', '4444522'], 
          dtype='|S7')
    

    or, using map():

    In [8]: np.array(map(str, [0,33,4444522]))
    Out[8]: 
    array(['0', '33', '4444522'], 
          dtype='|S7')
    

提交回复
热议问题