查看链接位置的示例:
#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 是缩进敏感的。也就是说,缩进级别将决定 for 循环的主体,根据 thegrinner 的评论:
您的 data = np.array(data) 行是在循环中还是在循环之外存在巨大差异。
话虽这么说,以下应该证明差异:
>>> 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])
对比
>>> 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/