我试图加载/ Python中使用numpy的运行从test.mm文件的矩阵。该文件内的基质例如2×2矩阵作为写入
1 1 10
1 2 11
2 1 20
2 2 30
我研究了很多,但我无法找到合适的答案。
解
该代码是propably不是有史以来最好的,但它适用于你所提供的例子。此外,在蟒蛇指数从0开始,你有指标1,2其设3x3矩阵。我修改了它,虽然你的用例
import numpy as np
def mm2matrix(file_name,start_line = 1):
with open(file_name,'r') as f:
data = f.read().split('\n')
number = [i.split(' ') for i in data]
number = number[start_line:]
all_numbers = []
for i in range(len(number)):
all_numbers += [float(sub) for sub in number[i] if len(sub)!=0]
mmfile = np.array(all_numbers).reshape(len(all_numbers)/3,3,)
x_index = mmfile[:,0].astype(np.int)-1
y_index = mmfile[:,1].astype(np.int)-1 # you say 2x2 matrix, but you have indexes 1,2
matrix = np.zeros(shape = [np.amax(x_index)+1,np.amax(y_index)+1])
values = mmfile[:,2]
matrix[x_index,y_index]=values
return matrix
matrix = mm2matrix('test.mm')
>>> matrix
array([[10., 11., 22.],
[20., 45., 85.]])
test.mm - I增加了一个柱(2×3或3×2)进行测试的效果影响不大
Matrix
1 1 10
1 2 11
1 3 22
2 1 20
2 2 30
2 2 45
2 3 85
如果阵列已经切换轴,则只是调换它
matrix = matrix.T