Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

import text file as matrix in numpy

I am very new to python programming so this might look very easy for most of the pros out there. I have a text file in the following format. I want to import only the numbers to a matrix. Meaning i do not want the spaces (there is also a space at the start of each row) and the data label.

 1 1 1 1 1 1 1 data_1
 1 1 1 1 1 1 2 data_2
 1 1 1 1 1 2 1 data_3
 1 1 1 1 1 2 2 data_4
 1 1 1 1 1 3 1 data_5
 1 1 1 1 1 3 2 data_6
like image 631
Rashid Avatar asked Apr 14 '15 13:04

Rashid


1 Answers

Use numpy.loadtxt, which assumes the data are delimited by whitespace by default and takes an argument usecols specifying which fields to use in building the array:

In [1]: import numpy as np
In [2]: matrix = np.loadtxt('matrix.txt', usecols=range(7))
In [3]: print matrix

[[ 1.  1.  1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.  1.  2.]
 [ 1.  1.  1.  1.  1.  2.  1.]
 [ 1.  1.  1.  1.  1.  2.  2.]
 [ 1.  1.  1.  1.  1.  3.  1.]
 [ 1.  1.  1.  1.  1.  3.  2.]]

If you want your matrix elements to be integers, pass dtype=int to loadtxt as well.

like image 148
xnx Avatar answered Sep 26 '22 06:09

xnx