简体   繁体   中英

python save numpy array with only non-zero elements

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 ?.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM