我有一个这样的.txt
数据文件
1317 1 1.0
1318 2 1.0
1319 3 1.0
1320 4 1.0
191 5 0.25
998 5 0.25
第一和第二列分别代表矩阵的行和列。第三列代表元素的值。(即(1317,1)= 1.0,(1318,2)= 1.0,...)
我想从该数据创建numpy矩阵,但是我不确定如何创建它。有人可以告诉我该怎么做吗?
numpy.genfromtxt
将这些列读入三个一维数组: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
编辑:;的方法启发这个答案,你可以让genfromtxt
手柄的数据类型的任务,但结了结构化阵列,它可以通过一些花哨的索引来处理:
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
您可以忽略数据类型转换,并继续创建您感兴趣的数组并为其建立索引。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句