## saving numpy matrix in text file with indices

Question

I am trying to save a 2D matrix A to text file for each non-zero entry. I would like to save it in the below format,

For the (i,j)-th entry, one line as

```
row[i]::column[j]::A[i,j]
```

where row and column are 1D numpy array corresponding to rows and column indices

I tried,

```
np.savetxt(rel_file,(row,column,A),fmt='%d',delimiter="::",newline="\n");
```

But, since shape mismatches, i get error. I do not want to iterate over each row and column indices in a loop (I think it is too time consuming, i have 5000*5000 matrix).

Show source

## Answers to saving numpy matrix in text file with indices ( 2 )

In my first answer I display all values; with just the nonzeros it's even easier to create the column array.

`np.where`

does the trick==========

For all values:

Here's a start; it is iterative, but as I commented, so is

`np.savetxt`

.We could make a (n,3) array consisting of the indices and flattened values of

`A`

. But`savetxt`

would still iterate on it, effectively:Here's one way of making this 3 column array:

Heres a simple method that manually reshapes the original array to be a very long array consisting of

row, col, value. Just filter the rows for non-zero and it should work. The below example works with this random 50,50 array.