Python代码没有运行

时间:2013-06-03 14:23:07

标签: python python-2.7 numpy

我正在与this tutorial合作。在示例

import csv as csv

import numpy as np

csv_file_object = csv.reader(open('train.csv', 'rb'))

header = csv_file_object.next()

data = []

for row in csv_file_object:

data.append(row)

data = np.array(data)

我遇到以下错误:

  

追踪(最近一次呼叫最后一次):

     

文件“C:/ Users / Prashant / Desktop / data mining / demo.py”,第7行,

     模块data.append(row)中的

     

AttributeError:'numpy.ndarray'对象没有属性'append'

我用Google搜索并在append上找到this question/answer,但我没有得到任何内容。

3 个答案:

答案 0 :(得分:1)

查看linked location上的示例:

#The first thing to do is to import the relevant packages
# that I will need for my script, 
#these include the Numpy (for maths and arrays)
#and csv for reading and writing csv files
#If i want to use something from this I need to call 
#csv.[function] or np.[function] first

import csv as csv 
import numpy as np

#Open up the csv file in to a Python object
csv_file_object = csv.reader(open('../csv/train.csv', 'rb')) 
header = csv_file_object.next()  #The next() command just skips the 
                                 #first line which is a header
data=[]                          #Create a variable called 'data'
for row in csv_file_object:      #Run through each row in the csv file
    data.append(row)             #adding each row to the data variable
data = np.array(data)            #Then convert from a list to an array
                                 #Be aware that each item is currently
                                 #a string in this format

Python是indentation-sensitive。也就是说,缩进级别将确定for循环的主体,并根据grinner的注释:

  

您的数据= np.array(数据)行是在循环中还是在循环之外存在巨大差异。

据说以下内容应证明其不同之处:

>>> import numpy as np
>>> data = []
>>> for i in range(5):
...     data.append(i)
... 
>>> data = np.array(data) # re-assign data after the loop
>>> print data
array([0, 1, 2, 3, 4])

VS

>>> data = []
>>> for i in range(5):
...     data.append(i)
...     data = np.array(data) # re-assign data within the loop
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
AttributeError: 'numpy.ndarray' object has no attribute 'append'

作为旁注,我怀疑你所遵循的教程的质量是否适用于血腥的Python启动器。 我认为这个更基本的(官方)教程应该更适合快速首次概述该语言:http://docs.python.org/2/tutorial/

答案 1 :(得分:0)

好吧,看看你问到的另一个问题的链接,看起来numpy.ndarray没有名为append的属性,但它看起来像NumPy。

所以改为使用:

numpy.append()

或者你可以尝试连接。

查看Stack Overflow问题 Append a NumPy array to a NumPy array

答案 2 :(得分:0)

检查缩进。如果{for循环中有data = np.array(data)(即缩进与data.append(row)相同的数量),则在将项目附加到列表之前,您将data变为Numpy数组。< / p>

这将导致您看到的错误,因为列表具有append()方法,而numpy数组则不会。你的for循环应该看起来像

data = [] # Make data a list 
for row in csv_file_object: #iterate through rows in the csv and append them to the list
    data.append(row)

# Turn the list into an array. Notice this is NOT indented! If it is, the data
# list will be overwritten!
data = np.array(data)

检查Dive Into Python以获得有关缩进在Python中如何工作的更广泛说明。