Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If your data file is structured like this</p> <pre><code>col1, col2, col3 1, 2, 3 10, 20, 30 100, 200, 300 </code></pre> <p>then <code>numpy.genfromtxt</code> can interpret the first line as column headers using the <code>names=True</code> option. With this you can access the data very conveniently by providing the column header:</p> <pre><code>data = np.genfromtxt('data.txt', delimiter=',', names=True) print data['col1'] # array([ 1., 10., 100.]) print data['col2'] # array([ 2., 20., 200.]) print data['col3'] # array([ 3., 30., 300.]) </code></pre> <p>Since in your case the data is formed like this</p> <pre><code>row1, 1, 10, 100 row2, 2, 20, 200 row3, 3, 30, 300 </code></pre> <p>you can achieve something similar using the following code snippet:</p> <pre><code>labels = np.genfromtxt('data.txt', delimiter=',', usecols=0, dtype=str) raw_data = np.genfromtxt('data.txt', delimiter=',')[:,1:] data = {label: row for label, row in zip(labels, raw_data)} </code></pre> <p>The first line reads the first column (the labels) into an array of strings. The second line reads all data from the file but discards the first column. The third line uses dictionary comprehension to create a dictionary that can be used very much like the structured array which <code>numpy.genfromtxt</code> creates using the <code>names=True</code> option:</p> <pre><code>print data['row1'] # array([ 1., 10., 100.]) print data['row2'] # array([ 2., 20., 200.]) print data['row3'] # array([ 3., 30., 300.]) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload