简体   繁体   English

在Python中:如何将稀疏矩阵写入CSV文件?

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

I am a newbie to Python. 我是Python的新手。 I have been given a script which generates random numbers and puts them in a 126x81 sparse matrix. 我得到了一个脚本,该脚本生成随机数并将其放入126x81稀疏矩阵中。 I would like to generate a csv file with: Cell_ID ; 我想使用以下代码生成一个csv文件: Cell_ID ; Cell_X ; Cell_X ; Cell_Y ; Cell_Y ; Val . Cell X and Y are of course the coordinates for each cell. 单元格X和Y当然是每个单元格的坐标。 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). 我有一个脚本,该脚本具有一个生成“ outputs.csv”文件的循环,但其中的数据并未按照我想要的方式显示(每行的开头/结尾都有方括号,并且省略号[... ]代替某些值)。 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. 如果可以的话,我将上传一张图片,向您展示在记事本或Excel中读取这些数据时的外观,但我不允许这样做。 However, these data should look like a typical csv file with each value aligned under its column. 但是,这些数据应看起来像典型的csv文件,每个值在其列下对齐。 Thank you for your help guys! 谢谢您的帮助! :) :)

Since the standard library supports csv, let's use it: 由于标准库支持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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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