Converting int arrays to string arrays in numpy without truncation

前端 未结 5 1483
野的像风
野的像风 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:07

    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'], 
          dtype='|S7')
    
    0 讨论(0)
  • 2020-12-08 03:07

    Use arr.astype(str), as int to str conversion is now supported by numpy with the desired outcome:

    import numpy as np
    
    a = np.array([0,33,4444522])
    
    res = a.astype(str)
    
    print(res)
    
    array(['0', '33', '4444522'], 
          dtype='<U11')
    
    0 讨论(0)
  • 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')
    
    0 讨论(0)
  • 2020-12-08 03:16

    np.apply_along_axis(lambda y: [str(i) for i in y], 0, x)

    Example

    >>> import numpy as np
    
    >>> x = np.array([-1]*10+[0]*10+[1]*10)
    array([-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  0,  0,  0,  0,  0,  0,  0,
            0,  0,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1])
    
    >>> np.apply_along_axis(lambda y: [str(i) for i in y], 0, x).tolist()
    ['-1', '-1', '-1', '-1', '-1', '-1', '-1', '-1', '-1', '-1', '0', '0',
     '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1',
     '1', '1', '1', '1']
    
    0 讨论(0)
  • 2020-12-08 03:19

    You can stay in numpy, doing

    np.char.mod('%d', a)
    

    This is twice faster than map or list comprehensions for 10 elements, four times faster for 100. This and other string operations are documented here.

    0 讨论(0)
提交回复
热议问题