【问题标题】:make a full matrix output in python在python中制作完整的矩阵输出
【发布时间】:2015-06-06 03:17:01
【问题描述】:

我有一个 236 x 97 维度的矩阵。当我在 Python 中打印矩阵时,它的输出不完整,矩阵中间有 .......

我尝试将矩阵写入测试文件,但结果完全相同。 我无法发布屏幕截图,因为我的声誉不够,如果我选择其他标记选项,将无法正确显示。 谁能解决这个问题?


 def build(self):
    self.keys = [k for k in self.wdict.keys() if len(self.wdict[k]) > 1]
    self.keys.sort()
    self.A = zeros([len(self.keys), self.dcount])
    for i, k in enumerate(self.keys):
        for d in self.wdict[k]:
            self.A[i,d] += 1

 def printA(self):
    outprint = open('outputprint.txt','w')
    print 'Here is the weighted matrix'
    print self.A
    outprint.write('%s' % self.A)
    outprint.close()
    print self.A.shape

【问题讨论】:

    标签: python python-2.7 matrix python-2.x


    【解决方案1】:

    假设您的矩阵是一个 numpy 数组,您可以使用 matrix.tofile(<options>) 将数组写入文件,如 here 所述:

    #!/usr/bin/env python
    # coding: utf-8
    
    import numpy as np
    
    # create a matrix of random numbers and desired dimension
    a = np.random.rand(236, 97)
    
    # write matrix to file
    a.tofile('output.txt', sep = ' ')
    

    【讨论】:

    • 它实际上可以工作,但是输出的值与我在 python shell 中打印的输出不同。我错过了什么吗?
    • @IrfanDary:你所说的“与众不同”到底是什么意思?实际上,stdout 上的输出被缩短了。如果我解决了你的问题,你能在我的回答上打勾吗?
    • 我的意思是这个值与shell中的输出不同。我从文本文件中获取了一个值,然后在 shell 中搜索该值,但找不到相同的值。
    • @IrfanDary:我不确定,但也许这是由于减少了precision on stdout?为了证明这一点,请仔细检查 shell 中的值和输出文件中的值。
    【解决方案2】:

    问题是您专门将str 表示保存到具有此行的文件中:

    outprint.write('%s' % self.A)

    将其显式转换为字符串 (%s) --- 生成您所看到的精简版本。

    有很多方法可以将整个矩阵写入输出,一个简单的选择是使用numpy.savetxt,例如:

    import numpy
    numpy.savetxt('outputprint.txt', self.A)
    

    【讨论】:

    • 它是否与 2.7 版本兼容,或者我应该从 numpy 导入一些东西?因为当我尝试这个时它变成了错误。它说“NameError:未定义全局名称'numpy'”
    • @IrfanDary 您必须先导入 numpy 模块 --- 我已将相关行添加到我的答案中。所有模块必须先导入才能使用。如果您有兴趣,请查看this simple tutorial on modules
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-16
    • 2023-03-12
    • 2013-10-05
    • 2013-08-01
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多