Taking file input in numpy Matrix
<p>I am unable to find a method to take input of a given file in numpy matrix. 
I have tried the <code>np.loadtxt()</code> but was unable to get the data.</p>

<p>My file format is something like this: 
Number of col = 9 (except the first field all others are in float).</p>

<pre><code>M,0.475,0.37,0.125,0.5095,0.2165,0.1125,0.165,9
F,0.55,0.44,0.15,0.8945,0.3145,0.151,0.32,19
</code></pre>

<p>I have also tried taking input in a list and then trying to make it numpy matrix but it was also a failure. </p>

<p>With your sample as a list of lines:</p>

<pre><code>In [1]: txt=b"""
   ...: M,0.475,0.37,0.125,0.5095,0.2165,0.1125,0.165,9
   ...: F,0.55,0.44,0.15,0.8945,0.3145,0.151,0.32,19
   ...: """
In [2]: txt=txt.splitlines()
</code></pre>

<p><code>genfromtxt</code> can load it with <code>dtype=None</code>:</p>

<pre><code>In [16]: data = np.genfromtxt(txt, delimiter=',', dtype=None)
In [17]: data
Out[17]: 
array([(b'M', 0.475, 0.37, 0.125, 0.5095, 0.2165, 0.1125, 0.165, 9),
       (b'F', 0.55, 0.44, 0.15, 0.8945, 0.3145, 0.151, 0.32, 19)], 
      dtype=[('f0', 'S1'), ('f1', '&lt;f8'), ('f2', '&lt;f8'), ('f3', '&lt;f8'), ('f4', '&lt;f8'), ('f5', '&lt;f8'), ('f6', '&lt;f8'), ('f7', '&lt;f8'), ('f8', '&lt;i4')])
In [18]: data['f0']
Out[18]: 
array([b'M', b'F'], 
      dtype='|S1')
In [19]: data['f3']
Out[19]: array([ 0.125,  0.15 ])
In [20]: 
</code></pre>

<p>The result is a 1d array (here 2 elements), with many fields, which are accessed by name.  Here the first is deduced to be a string, the rest float, except the last integer.</p>

<p>I could be more specific about the <code>dtype</code>, and define a field with multiple columns</p>

<pre><code>In [21]: data=np.genfromtxt(txt,delimiter=',',dtype=['S3','8float'])
In [22]: data
Out[22]: 
array([(b'M', [0.475, 0.37, 0.125, 0.5095, 0.2165, 0.1125, 0.165, 9.0]),
       (b'F', [0.55, 0.44, 0.15, 0.8945, 0.3145, 0.151, 0.32, 19.0])], 
      dtype=[('f0', 'S3'), ('f1', '&lt;f8', (8,))])
In [23]: data['f1']
Out[23]: 
array([[  0.475 ,   0.37  ,   0.125 ,   0.5095,   0.2165,   0.1125,
          0.165 ,   9.    ],
       [  0.55  ,   0.44  ,   0.15  ,   0.8945,   0.3145,   0.151 ,
          0.32  ,  19.    ]])
</code></pre>

<p>The <code>f1</code> field is a 2d array of shape (2,8).</p>

<p><code>np.loadtxt</code> will also work, but it's <code>dtype</code> interpretation isn't as flexible.  Copying the <code>dtype</code> from the <code>genfromtxt</code> example produces the same thing.</p>

<pre><code> datal=np.loadtxt(txt,delimiter=',',dtype=data.dtype)
</code></pre>

<p><code>pandas</code> also has a good csv reader, with more speed and flexibility.  It's a good choice if you are already working with pandas.</p>

python numpy