Search code examples
pythonnumpyscalar

how to make use of Python scalars correctly?


>>> numpy.sin(range(11))
array([ 0.        ,  0.84147098,  0.90929743,  0.14112001, -0.7568025
   -0.95892427, -0.2794155 ,  0.6569866 ,  0.98935825,  0.4121184
   -0.54402111])
>>> numpy.array(range(11))*2
array([ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20]) 
>>> str(numpy.array(range(11))... )
'[ 0  1  2  3  4  5  6  7  8  9 10]'

how can I get ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] with the concept of python scalars such as numpy.sin(range(11)) or numpy.array(range(11))*2?

I can do that with following:

>>> s=[]
>>> [s.append(str(i)) for i in range(11)]
>>> s
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

>>> str(numpy.array(range(11)))
'[ 0  1  2  3  4  5  6  7  8  9 10]'

what I want is ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] , not '[ 0 1 2 3 4 5 6 7 8 9 10]' .

It gets the string array with the concept of list comprehension, how can get the work done by the concept--python scalars?


Solution

  • I think this is what you want:

    >>> a = numpy.arange(10)
    >>> a
    array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    
    >>> a.astype(str)
    array(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], 
          dtype='|S21')