【问题标题】:Which argument is required for np.savetxt to output float data?np.savetxt 输出浮点数据需要哪个参数?
【发布时间】:2015-09-04 23:37:41
【问题描述】:

我有一段运行良好的代码,但是我正在努力确定将其输出到 .txt 文件中的方法。代码如下:

with open("Coord") as f:
    line=f.readline()
    for line in f:
        coords=map(float,line.split(" "))
        if poly.contains(Point(coords[0],coords[1])):
            print line

打印命令可以工作并在终端中显示我需要的内容,但是我还没有找到保存它的方法。到目前为止,这是我尝试过的:

np.savetxt('inside.txt', np.vstack((line.str())).T)

AttributeError: 'str' object has no attribute 'str'

np.savetxt('inside.txt', line)

IndexError: tuple index out of range

np.savetxt('inside.txt', np.transpose([line])

TypeError: float argument required, not numpy.string_

np.savetxt('inside.txt', line, delimiter=" ", fmt="%s")

IndexError: tuple index out of range

我对 python 和一般代码仍然缺乏经验,希望有人能解释这里使用的正确格式。提前致谢。

【问题讨论】:

  • 您可能需要检查documentationthis question
  • 我在发帖前已经检查了两者。另一个线程是我第 4 次列出的尝试,我无法从文档中解决它。我刚试过 ...fmt="%f" 但也没有用。
  • 只是为了确定 - line numpy 数组对象在这里是 np.savetxt('inside.txt', line) 吗?你能显示它的数据吗?
  • @erthalion 在执行完其余代码后,我可以使用命令“打印行”,它会在终端屏幕上准确显示我想要的内容 - 我只是不知道如何保存它数据到文本文件。
  • @Vlad AttributeError: 'str' object has no attribute 'str' 这意味着,line 是一个字符串(当然,它是一行文件)。但正如您在文档中看到的那样,np.savetxt 需要 numpy 数组作为第二个参数,而不仅仅是一个字符串。

标签: python numpy


【解决方案1】:

documentation 可以清楚地看到 np.savetext 需要一个 array_like 对象作为第二个参数。

您可以尝试在保存之前将line 转换为array,例如 -

np.savetxt('inside.txt', np.array(line.split(" ")), delimiter=" ", fmt="%s")

【讨论】:

  • 作为一个小测试,您可以尝试使用 np.savetxt('inside.txt', line.split(" "), delimiter=" ", fmt="%s") ,我们可以检查它是否也接受列表作为输入,我的猜测是否定的,但如果运气好的话,我们可以避免对np.array()的开销调用
  • 感谢您的回答和解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-16
  • 1970-01-01
  • 1970-01-01
  • 2018-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多