mohammad jcm
mohammad jcm

Reputation: 31

how to write a matrix to a file in python with this format?

I need to write a matrix to a file with this format (i, j, a[i,j]) row by row, but I don't know how to get it. I tried with: np.savetxt(f, A, fmt='%1d', newline='\n'), but it write only matrix values and don't write i, j!

Upvotes: 1

Views: 1405

Answers (2)

xnx
xnx

Reputation: 25548

If your array datatype is not a sort of integer, you'll probably have to write your own function to save it along with its indices, since these are integers. For example,

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

Upvotes: 1

unutbu
unutbu

Reputation: 880459

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')

writes to /tmp/out the contents

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

Upvotes: 2

Related Questions