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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With