S.Ky
S.Ky

Reputation: 169

create matrix from txt data

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

Answers (1)

amzon-ex
amzon-ex

Reputation: 1744

rows, cols, data = np.genfromtxt('test.txt', unpack = True)
  • Convert to appropriate datatypes:
rows = rows.astype(int)
cols = cols.astype(int)
  • Create the array of interest with the required size:
a = np.empty((np.max(rows)+1, np.max(cols)+1))
  • Index and assign:
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

Related Questions