Question

Suppose I have the following string.

 irb(main):074:0> line = "#!/usr/bin/ruby\n#\n#  Gen"
 irb(main):078:0> NArray.to_na(line,Float)
 => NArray.float(3): 
 [ 9.05457e+164, 3.30198e-258, 6.1531e+223 ]

How do I mimic this behavior with Python using numpy.array?

I tried the following, but it did not work.

>>> line = '#!/usr/bin/ruby\n#\n#  Gen'
>>> np.array(line,float)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: #!/usr/bin/ruby
#
#  Gen

Then I tried to convert it to bytes, but that did not work either.

>>> bytes = bytearray(line, 'utf-8')
>>> np.array(bytes,float)
array([  35.,   33.,   47.,  117.,  115.,  114.,   47.,   98.,  105.,
        110.,   47.,  114.,  117.,   98.,  121.,   10.,   35.,   10.,
         35.,   32.,   32.,   71.,  101.,  110.])

How do I resolve this?

Was it helpful?

Solution

You can easily achieve this by using the fromstring method of numpy:

import numpy as np

line = "#!/usr/bin/ruby\n#\n#  Gen"
array = np.fromstring(line, dtype=float)
print array

Executing the above code results in

[  9.05457127e+164   3.30197767e-258   6.15310337e+223]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top