Shew
Shew

Reputation: 1596

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

Upvotes: 1

Views: 1700

Answers (1)

kevinkayaks
kevinkayaks

Reputation: 2726

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

Upvotes: 3

Related Questions