How to get a numpy ndarray of integers from a file with header?
<p>I have a plain text file (.txt) with the following content.</p>

<pre><code>Matrix Header.
6 11
0 1 1 1 1 1 1 1 1 1 1 
1 0 1 1 1 1 0 1 1 1 1 
1 1 1 1 0 0 1 1 1 1 1 
0 0 0 0 1 1 1 0 0 0 0 
1 1 1 0 0 1 1 1 1 1 1 
1 0 0 1 1 1 1 0 1 1 0 

 6 rows,  11 columns
</code></pre>

<p>I need obtain a numpy ndarray of integers as below:</p>

<pre><code>[[0 1 1 1 1 1 1 1 1 1 1] 
 [1 0 1 1 1 1 0 1 1 1 1] 
 [1 1 1 1 0 0 1 1 1 1 1] 
 [0 0 0 0 1 1 1 0 0 0 0] 
 [1 1 1 0 0 1 1 1 1 1 1] 
 [1 0 0 1 1 1 1 0 1 1 0]]
</code></pre>

<p>I tried the following strategy</p>

<pre><code>import pandas
import numpy
data = pandas.read_table(path, skiprows= 2)
data = data.values
print(data)
</code></pre>

<p>But the resulting ndarray isn't in the correct format.</p>

<pre><code>[['0 1 1 1 1 1 1 1 1 1 1 '] 
 ['1 0 1 1 1 1 0 1 1 1 1 '] 
 ['1 1 1 1 0 0 1 1 1 1 1 '] 
 ['0 0 0 0 1 1 1 0 0 0 0 '] 
 ['1 1 1 0 0 1 1 1 1 1 1 '] 
 ['1 0 0 1 1 1 1 0 1 1 0 ']]
</code></pre>

<p>Can anybody help me?</p>

<p>To avoid the error that might occur because of the text at the end, you can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html" rel="nofollow"><code>numpy.genfromtxt</code></a> with the <code>max_rows</code> argument.  For example,</p>

<pre><code>In [26]: with open(filename, 'rb') as f:
    ...:     f.readline()  # skip the header
    ...:     nrows, ncols = [int(field) for field in f.readline().split()]
    ...:     data = np.genfromtxt(f, dtype=int, max_rows=nrows)
    ...:     

In [27]: data
Out[27]: 
array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
       [1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1],
       [1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1],
       [0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0],
       [1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1],
       [1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0]])
</code></pre>

<p>(I opened the file in binary mode to avoid a bytes/str problem that <code>genfromtxt</code> has in Python 3.)</p>

python numpy multidimensional-array