In Python: how to write a sparse matrix to a csv file?

时间:2015-07-28 16:03:53

标签: python excel csv matrix matplotlib

I am a newbie to Python. I have been given a script which generates random numbers and puts them in a 126x81 sparse matrix. I would like to generate a csv file with: Cell_ID; Cell_X; Cell_Y; Val. Cell X and Y are of course the coordinates for each cell. The script I have has a loop which generates an "outputs.csv" file, but in it data are not displayed the way I want them (there are square brackets at the beginning/end of each line and there are ellipsis [...] in place of some values). To sum up, I am not able to read the whole content of the matrix.

If I could, I would upload a picture to show you how I would like these data to look like when read in Notepad or Excel, but I am not allowed to do so. However, these data should look like a typical csv file with each value aligned under its column. Thank you for your help guys! :)

1 个答案:

答案 0 :(得分:2)

由于标准库支持csv,因此我们使用它:

import numpy
import csv

N = 126
M = 81

g = numpy.random.rand(N, M)

with open('test.csv', 'w') as f:
    writer = csv.writer(f)
    writer.writerow(['x', 'y', 'value'])
    for (n, m), val in numpy.ndenumerate(g):
        writer.writerow([n, m, val])