TypeError:'int'对象不可迭代// numpy

时间:2013-09-29 08:35:58

标签: python arrays numpy

这是我的功能:

import numpy as np
def calc_mean():
    return np.loadtxt('GOOG.csv', skiprows=1, usecols=(6)).mean(axis=0)

这是我的GOOG.csv

Date        Open    High    Low     Close   Volume     Adj Close # <-- column that I need
2013-09-27  874.82  877.52  871.31  876.39  1258800    876.39
2013-09-26  878.3   882.75  875     878.17  1259900    878.17
2013-09-25  886.55  886.55  875.6   877.23  1649000    877.23
2013-09-24  886.5   890.1   881.4   886.84  1467000    886.84
2013-09-23  896.15  901.59  885.2   886.5   1777400    886.5
2013-09-20  898.39  904.13  895.62  903.11  4345300    903.11
2013-09-19  905.99  905.99  895.4   898.39  1597900    898.39
2013-09-18  886.35  903.97  883.07  903.32  1934700    903.32
2013-09-17  887.41  888.39  881     886.11  1259400    886.11
2013-09-16  896.2   897     884.87  887.76  1336500    887.76
.............................................................
end of file:
.............................................................
2012-06-29  574.96  58013   572.20  580.07  2519500    580.07
2012-06-28  565.90  566.23  557.21  564.31  1920900    564.31
2012-06-27  567.70  573.99  566.02  569.30  1692300    569.30
2012-06-26  562.76  566.60  559.48  564.68  1350200    564.68
2012-06-25  567.33  568.09  557.35  560.70  1581600    560.70

当我运行它时,我有以下错误:

  Traceback (most recent call last):
File "/home/misha/Documents/finance/finance.py", line 164, in <module>
  security_mean(file_list)
File "/home/misha/Documents/finance/finance.py", line 125, in security_mean
  return np.loadtxt('GOOG.csv', skiprows=1, usecols=(6)).mean(axis=0)
File "/usr/lib/python2.7/site-packages/numpy/lib/npyio.py", line 703, in loadtxt
  usecols = list(usecols)
TypeError: 'int' object is not iterable 

我该如何解决?

如果我在usecols=(6)usecols=(6,)上更改usecols=([6]),则会出现以下错误:

Traceback (most recent call last):
  File "/home/misha/Documents/finance/finance.py", line 164, in <module>
    security_mean(file_list)
  File "/home/misha/Documents/finance/finance.py", line 125, in security_mean
    return np.loadtxt('GOOG.csv', skiprows=1, usecols=([6])).mean(axis=0)
  File "/usr/lib/python2.7/site-packages/numpy/lib/npyio.py", line 825, in loadtxt
    vals = [vals[i] for i in usecols]
IndexError: list index out of range

感谢。

注意: GOOG.csv中的所有数据均为strings

2 个答案:

答案 0 :(得分:8)

usecols参数应该是可迭代的:

usecols=(5,) # or [5]

请注意,(5) 是单元素元组。它简直等于5,(逗号)是构建元组的重要因素。

答案 1 :(得分:1)

使用(5)不会创建任何类型的元组或可迭代。您必须在(5,)参数中使用[5]usecols