【问题标题】:getting error to save the Matrix in txt file using numpy numpy使用 numpy numpy 将矩阵保存在 txt 文件中时出错
【发布时间】:2017-09-10 21:21:56
【问题描述】:

我已经编写了这段代码来创建一个数组=>

import numpy as np
a = np.array([[[1,3],[1,4]],[[1,4],[6,9]]])
np.savetxt('test.txt',a,fmt='%d')

并得到这个错误 =>

Traceback(最近一次调用最后一次):文件 “/usr/local/lib/python3.4/dist-packages/numpy-1.11.2-py3.4-linux-x86_64.egg/numpy/lib/npyio.py”, 第 1158 行,在 savetxt 中 fh.write(asbytes(format % tuple(row) + newline)) TypeError: %d format: a number is required, not numpy.ndarray

在处理上述异常的过程中,又发生了一个异常:

Traceback(最近一次调用最后一次):文件“”,第 1 行,in 文件 “/usr/local/lib/python3.4/dist-packages/numpy-1.11.2-py3.4-linux-x86_64.egg/numpy/lib/npyio.py”, 第 1162 行,在 savetxt 中 % (str(X.dtype), format)) TypeError: 数组 dtype ('int64') 和格式说明符 ('%d %d') 不匹配

如何使用 numpy 将数组保存为文件中的整数?

【问题讨论】:

  • 您希望输出文件采用什么样的结构?你能发布你想要的吗?
  • @roganjosh 我想将该矩阵保存在该 txt 文件中
  • 您有一个 3d 数组,请尝试保存 a.reshape(-1, 2)np.savetxt('test.txt',a.reshape(-1,2),fmt='%d')
  • 好的,谢谢你帮助我。完美的@Psidom

标签: python numpy


【解决方案1】:
%d format: a number is required, not numpy.ndarray

基本上你不能在对象/类/what-have-you 上使用格式字符串;它需要一个数字,而不是一个数字数组

将数组转换为可打印的字符串。同样,您不能真正将整数保存在文件中,只能将字符串保存在文件中。

您需要做的是获取数组中的每一行并将其写入文件,类似于以下内容:

to_write = ''
for small_list in list_of_lists:
    to_write += ''.join(small_list, ',') + "\n"
my_file.write(to_write)

【讨论】:

  • 如果我想加载这个矩阵我会怎么做??
【解决方案2】:

我不确定你想要什么样的输出......

你可以这样做

F = open('test.txt', 'w')
for i in a:
    for j in i:
        line = '%s \t %s \n'%(j[0], j[1])
        F.write(line)

F.close()

会给你

1 3

1 4

1 4

6 9

【讨论】:

  • 如果我想加载这个矩阵我会怎么做??
  • 那么你可以使用numpy.genfromtxt('test.txt')
  • 请不要因为@Psidom 的评论会以更 numpythonic 的方式给你与我的提议相同的建议
  • 是的,但是您已经发布了从文件加载矩阵非常困难的帖子。但是如果我使用那个,那很好,因为 numpy 中有一个函数 loadtxt()。那我为什么要用这个
  • numpy.genfromtxt()numpy.loadtxt()的区别可以看there
【解决方案3】:

这个问题有个老帖子

Saving numpy array to csv produces TypeError Mismatch

如果您检查,您的数组是导致问题的 3D 数组

1.如果您将其转换为 2D,它将起作用

将 numpy 导入为 np a = np.array([[[1,3],[1,4]],[[1,4],[6,9]]]) np.savetxt('test.txt',a.reshape(-1,a.shape[-1]),fmt="%d")

2。如果你一次写一行,它也可以工作

但这会在回读时出现问题

我的建议,写成dict/json,看完后转成numpy

【讨论】:

    猜你喜欢
    • 2017-07-13
    • 2014-08-25
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    • 2010-12-14
    • 1970-01-01
    • 2018-12-15
    • 1970-01-01
    相关资源
    最近更新 更多