Loading numpy array from string

Okay children, today we learn how to convert text to numpy matrix.
Source is here.


# loading modules
import numpy
from StringIO import StringIO

# Using StringIO as a file-like wrapper over text
I0 = numpy.loadtxt(StringIO("""
         0         0         0         0         0
         0         0    0.5000         0         0
         0         0    1.0000         0         0
         0         0    0.5000         0         0
         0    1.0000         0         0         0
         0    0.5000         0         0         0
         0    0.5000    1.0000         0         0
         0         0         0         0         0""") )


I1 = numpy.loadtxt(StringIO("""
         0         0         0         0         0
         0    0.5000         0         0         0
         0    1.0000         0         0         0
         0    0.5000         0         0         0
         0         0    1.0000         0         0
         0         0    0.5000         0         0
         0         0    0.5000    1.0000         0
         0         0         0         0         0 """) )
#printing results:
print I0
print I1

#result
[[ 0.   0.   0.   0.   0. ]
 [ 0.   0.   0.5  0.   0. ]
 [ 0.   0.   1.   0.   0. ]
 [ 0.   0.   0.5  0.   0. ]
 [ 0.   1.   0.   0.   0. ]
 [ 0.   0.5  0.   0.   0. ]
 [ 0.   0.5  1.   0.   0. ]
 [ 0.   0.   0.   0.   0. ]]
[[ 0.   0.   0.   0.   0. ]
 [ 0.   0.5  0.   0.   0. ]
 [ 0.   1.   0.   0.   0. ]
 [ 0.   0.5  0.   0.   0. ]
 [ 0.   0.   1.   0.   0. ]
 [ 0.   0.   0.5  0.   0. ]
 [ 0.   0.   0.5  1.   0. ]
 [ 0.   0.   0.   0.   0. ]]


No comments:

Post a Comment