【问题标题】:numpy.loadtxt gives "not iterable" errornumpy.loadtxt 给出“不可迭代”错误
【发布时间】:2012-05-25 17:12:32
【问题描述】:

我正在尝试使用numpy.loadtxt 读取文件中的数据,如下所示:

## 14 line of header
3 0 36373.7641026
3 1 36373.7641026
3 2 36373.7641026
...

当我给它这个时:

>>> chunk, power = numpy.loadtxt(bf,skiprows=14,usecols=(1,2),unpack=True)

甚至这个:

>>> power = numpy.loadtxt(bf,skiprows=14,usecols=(2))

上面写着TypeError: 'int' object is not iterable

我认为这是因为前两列显然是整数而不是浮点数,但现在我什至不确定它指的是哪个 int 对象,因为它甚至不会只读取浮点数。如何让loadtxt 工作?

相关:如何使用dtype = ? 指定多列的格式我无法通过 google 弄清楚。

【问题讨论】:

    标签: python input numpy


    【解决方案1】:

    在您的第二个示例中,问题可能出在usecols=(2)usecols 必须是一个序列。 (2) 是整数 2,而不是包含 2 的单元素元组,这很可能是错误消息所抱怨的:loadtxt() 正在尝试迭代 int。使用(2,)(或[2],如果您愿意)。

    【讨论】:

    • usecols 是指定要读取哪些列的选项。见:docs.scipy.org/doc/numpy-1.4.x/reference/generated/…
    • @LoonUnit:我当然明白usecols 是什么,所以我知道它一定是一个序列。正如我在回答中所说,(2) 不是一个序列,它是整数 2。
    • 好的,朋友解释了你的答案,最终是正确的。 usecols=(2,) 确实有效。
    【解决方案2】:

    在这种情况下,很难知道是什么导致了问题,因为您没有向我们提供足够的信息。鉴于您在此处发布的内容,您的代码应该可以工作:

    >>> with open('beamtest.out', 'r') as f:
    ...     f.readlines()
    ... 
    ['header 0\n', 'header 1\n', 'header 2\n', 'header 3\n', 'header 4\n', 
     'header 5\n', 'header 6\n', 'header 7\n', 'header 8\n', 'header 9\n', 
     'header 10\n', 'header 11\n', 'header 12\n', 'header 13\n', 
     '3 0 36373.7641026\n', '3 1 36373.7641026\n', '3 2 36373.7641026']
    >>> chunk, power = numpy.loadtxt('beamtest.out', skiprows=14,
                                     usecols=(1,2), unpack=True)
    >>> chunk
    array([ 0.,  1.,  2.])
    >>> power
    array([ 36373.7641026,  36373.7641026,  36373.7641026])
    

    当然,正如kindall 的回答所示,您的第二个示例将失败,因为usecols 不接受单个整数;它requires a sequence。 ((1) 只是括号中的1;要创建一个元组,您需要在其中添加一个逗号——(1,)。)

    下面是一个如何使用dtype指定多列格式的例子:

    >>> record = numpy.loadtxt('beamtest.out', skiprows=14, usecols=(1, 2), 
                               dtype={'names':('chunk', 'power'), 
                                      'formats':('i8', 'f8')}) 
    >>> record
    array([(0, 36373.7641026), (1, 36373.7641026), (2, 36373.7641026)], 
          dtype=[('chunk', '<i8'), ('power', '<f8')])
    >>> record['chunk']
    array([0, 1, 2])
    >>> record['power']
    array([ 36373.7641026,  36373.7641026,  36373.7641026])
    

    【讨论】:

    • bf 只是一个文件名,bf = "beamtest.out"
    • @LoonUnit,看看我的编辑。它至少回答了您问题的第二部分(关于dtype)。我测试了您的第一个示例,它应该可以完美运行。
    • 是的,从长远来看,我想我最终会使用你的答案。
    猜你喜欢
    • 2017-06-12
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    相关资源
    最近更新 更多