1

I have an array with most of the elements are zero.

A =  [ 1,0,2
       2,3,0
       0,0,4 ]

I want to save this as

rowid[0] colid[0] 1
rowid[0] colid[2] 2
rowid[1] colid[0] 2
rowid[1] colid[1] 3
rowid[2] colid[2] 4

here rowid and colid are arrays which maps the array indices to the actual entries in an original file.

How can I do this without using a for loop ?.

5
  • There is a scipy.sparse package that handles matrices like this. Commented Sep 13, 2018 at 6:33
  • @hpaulj, i am looking for a way to write such an array in a plaintext file in the specified format Commented Sep 13, 2018 at 6:38
  • Should be easy iterating through argwhere.with your own line formatting. Commented Sep 13, 2018 at 6:53
  • Do you want your output to literally have the string "rowid[0]" etc. ? Commented Sep 13, 2018 at 7:11
  • Come to think of it, savetxt could be used a fancier format such as fmt='row[%d] col[%d] %d' Commented Sep 15, 2018 at 0:06

1 Answer 1

3
A = np.array(A).reshape(3, 3) # make A a 3x3 numpy array 
i, j = np.where(A != 0) # find indices where it is nonzero 
v = A[i, j] # extract nonzero values of the array 
np.savetxt('file.csv', np.vstack((i, j, v)).T, delimiter = ',') # stack and save 

# @Daniel F suggestion is to make header with array shape and add delimiter kwarg
np.savetxt('file.csv', np.vstack((i, j, v)).T, delimiter = ',', header = str(A.shape))
Sign up to request clarification or add additional context in comments.

3 Comments

Probably want a header value in savetxt to store the original shape of the array, so it can be rebuilt correctly if it is very sparse.
and to set delimiter = ','if you want a proper *.csv
Fixed a bit of formatting and added delimiter = ',' to your original answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.