Python 2.7 如何使用这种格式将矩阵写入python文件?
我需要将矩阵以这种格式逐行写入文件Python 2.7 如何使用这种格式将矩阵写入python文件?,python-2.7,numpy,scipy,Python 2.7,Numpy,Scipy,我需要将矩阵以这种格式逐行写入文件(I,j,a[I,j]),但我不知道如何获取它。我试过:np.savetxt(f,A,fmt='%1d',newline='\n'),但它只写矩阵值,不写I,j import numpy as np a = np.arange(12).reshape(4,3) a_with_index = np.array([idx+(val,) for idx, val in np.ndenumerate(a)]) np.savetxt('/tmp/out', a_with
(I,j,a[I,j])
,但我不知道如何获取它。我试过:np.savetxt(f,A,fmt='%1d',newline='\n')
,但它只写矩阵值,不写I,j
import numpy as np
a = np.arange(12).reshape(4,3)
a_with_index = np.array([idx+(val,) for idx, val in np.ndenumerate(a)])
np.savetxt('/tmp/out', a_with_index, fmt='%d')
将内容写入/tmp/out
0 0 0
0 1 10
0 2 20
1 0 30
1 1 40
1 2 50
2 0 60
2 1 70
2 2 80
3 0 90
3 1 100
3 2 110
如果数组数据类型不是整数类型,则可能需要编写自己的函数将其与其索引一起保存,因为这些是整数。比如说,
import numpy as np
def savetxt_with_indices(filename, arr, fmt):
nrows, ncols = arr.shape
indexes = np.empty((nrows*ncols, 2))
indexes[:,0] = np.repeat(np.arange(nrows), ncols)
indexes[:,1] = np.tile(np.arange(ncols), nrows)
fmt = '%4d %4d ' + fmt
flat_arr = arr.flatten()
with open(filename, 'w') as fo:
for i in range(nrows*ncols):
print(fmt % (indexes[i, 0], indexes[i, 1], flat_arr[i]), file=fo)
A = np.arange(12.).reshape((4,3))
savetxt_with_indices('test.txt', A, '%6.2f')
0 0 0.00
0 1 1.00
0 2 2.00
1 0 3.00
1 1 4.00
1 2 5.00
2 0 6.00
2 1 7.00
2 2 8.00
3 0 9.00
3 1 10.00
3 2 11.00
是否希望文件类似于:0 0 a[0,0]\n 0 1 a[0,1]\n等等?除非矩阵是稀疏的,否则是否有充分的理由需要此文件?如果是稀疏的,你可以看看这个