我有一个数组,其中大多数元素为零。
A = [ 1,0,2
2,3,0
0,0,4 ]
我想另存为
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
这里rowid和colid是数组,它们将数组索引映射到原始文件中的实际条目。
如何在不使用for循环的情况下执行此操作?
答案 0 :(得分: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))