Reputation: 169
I have a .txt
data file like this
1317 1 1.0
1318 2 1.0
1319 3 1.0
1320 4 1.0
191 5 0.25
998 5 0.25
The first and second columns represent the rows and columns of the matrix, respectively. The third columns represent the value of the elements. (i.e. (1317, 1) = 1.0, (1318, 2) = 1.0,...)
I want to create numpy matrix from this data, but I'm not sure how I can create it. Can someone tell me how to do it?
Upvotes: 1
Views: 58
Reputation: 1744
numpy.genfromtxt
to read those columns into three 1-D arrays:rows, cols, data = np.genfromtxt('test.txt', unpack = True)
rows = rows.astype(int)
cols = cols.astype(int)
a = np.empty((np.max(rows)+1, np.max(cols)+1))
a[rows, cols] = data
EDIT: Inspired by the method of this answer, you can let genfromtxt
handle datatype assignments, but end up with structured arrays, which can be handled by some fancy indexing:
c = np.genfromtxt('test.txt', dtype = None) # c is a recorded array (or structured array)
rows, cols, data = c['f%d'%0], c['f%d'%1], c['f%d'%2] # Addressing Array Columns by Name
The you can ignore the datatype conversion and continue with the creation and indexing of your array of interest.
Upvotes: 2