0

我正在使用本教程。关于示例

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,但我什么也没得到。

4

3 回答 3

1

查看链接位置的示例:

#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/

于 2013-06-03T14:44:20.107 回答
0

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

所以改为使用:

numpy.append()

或者你可以尝试连接。

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

于 2013-06-03T14:29:58.680 回答
0

检查你的缩进。如果data = np.array(data)在您的 for 循环中(即缩进与 相同的数量data.append(row)),您将data在完成将项目附加到列表之前变成一个 Numpy 数组。

这将导致您看到的错误,因为列表有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 中如何工作的更广泛的解释。

于 2013-06-03T14:36:52.710 回答