【问题标题】:Appending 2-D numpy array to txt file将二维 numpy 数组附加到 txt 文件
【发布时间】:2020-03-10 21:34:39
【问题描述】:

我的程序在执行时会打印一个变量predictions,它是一个二维 numpy 数组。我正在尝试将输出写入文本文件。我使用predictions.shape 确保形状是二维的,并使用type(predictions) 检查类型为<class numpy.ndarray>

我收到的错误是:

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    predictor()
  File "/Users/owner/Desktop/algo/predict.py", line 146, in predictor
    predictions.savetxt("predictions.txt", "a", delimiter=',', fmt='%d',  header='', footer='')
AttributeError: 'numpy.ndarray' object has no attribute 'savetxt'

这是我在python模块中调用函数后返回的。

我确定我正确导入了 numpy,我使用的 savetxt() 函数不正确吗?

我尝试在 Stack 上搜索,但找不到任何东西,谢谢。

【问题讨论】:

  • savetxt 是一个 numpy 函数,而不是数组方法。查看其文档。
  • “a”应该做什么?文档中没有关于此的内容。如果您不遵循文档,stack 搜索将无济于事。没有其他人不会以同样的方式跟随并得到同样的错误。
  • @hpaulj 我正在尝试附加到文件中,对不起,我应该更密切地关注文档
  • 可以以追加模式打开文件,并将其传递给loadtxt。

标签: python macos numpy tensorflow keras


【解决方案1】:

是的,savetext方法不是数组上的方法,而是numpy包中的方法。可以通过调用方法并传入数组来使用:

numpy.savetxt("predictions.txt", predictions, delimiter=',', fmt='%d',  header='', footer='')

或np.savetext(..),如果你这样做了import numpy as np

【讨论】:

  • 是的,谢谢你的话。还有一个问题,当我 print(predictions) 它返回 [[1654.676]] 时。但在文本文件中只出现“1654”。知道小数在哪里吗?这是 fmt 控制的吗?而且我希望添加到文件中而不是每次都重新编写它。谢谢
猜你喜欢
  • 2016-05-29
  • 1970-01-01
  • 2019-03-22
  • 1970-01-01
  • 2014-04-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多