numpy.savetxt“元组索引超出范围”?

时间:2012-11-06 16:57:14

标签: python

我正在尝试在文本文件中写几行,这是我使用的代码:

import numpy as np

# Generate some test data
data = np.arange(0.0,1000.0,50.0)

with file('test.txt', 'w') as outfile:      
    outfile.write('# something')

    for data_slice in data: 
        np.savetxt(outfile, data_slice, fmt='%1.4e')

        outfile.write('# New slice\n')

当代码运行到savetxt行时,我收到此错误:

     IndexError: tuple index out of range

知道为什么会这样吗?我尝试删除“fmt”部分,但我得到同样的东西。

1 个答案:

答案 0 :(得分:6)

问题是numpy.save期望一个包含一些形状信息的数组,而你只传递一个数字。

如果你想传递一个元素(但我建议你保存整个数组),你必须先将它转换成一个形状至少为一个的numpy数组

np.savetxt(outfile, array(data_slice).reshape(1,), fmt='%1.4e')

这是因为单个数字的形状是一个空元组,并且要写入文件,它会尝试沿第一个维度分割

array(1).shape == tuple()
#True

保存整个数组就足够了:

np.savetxt(outfile, data, fmt='%1.4e')
相关问题