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 ?.
U13-Forward
71.8k15 gold badges100 silver badges125 bronze badges
asked Sep 13, 2018 at 6:32
Shew
1,5961 gold badge24 silver badges43 bronze badges
1 Answer 1
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))
Daniel F
14.5k2 gold badges34 silver badges59 bronze badges
answered Sep 13, 2018 at 6:54
kevinkayaks
2,7561 gold badge17 silver badges30 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Daniel F
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.Daniel F
and to set
delimiter = ','if you want a proper *.csvDaniel F
Fixed a bit of formatting and added
delimiter = ',' to your original answerlang-py
argwhere.with your own line formatting."rowid[0]"etc. ?savetxtcould be used a fancier format such asfmt='row[%d] col[%d] %d'