在Python中转换列表输出

时间:2014-02-09 20:54:42

标签: python arrays list numpy scikit-learn

我有一个按如下方式工作的函数来读取.csv文件并将其存储在数组中。

def read_csv(self, filename, delimiter = ',', quotechar = '"'):
    reader = csv.reader(open(filename, 'rb'), delimiter = delimiter, quotechar = quotechar)
    # read first line and extract its data 
    self.column_headings = np.array(next(reader))
    # read subsequent lines
    rows = []
    for row in reader:
        rows.append(row)
    self.data = np.array(rows)
    self.m, self.n = self.data.shape

我只是想读取.tsv文件,以便它以相同的形式返回。到目前为止我有这个:

traindata = np.array(p.read_table('train.tsv'))[:,2]

然而,当我试着打电话时:

m, n = traindata.data.shape

# Display
print m, n, traindata.column_headings

我收到错误:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-14-1f877ccb37b5> in <module>()
----> 1 m, n = traindata.data.shape

AttributeError: 'buffer' object has no attribute 'shape'

导致此问题的原因是什么?如何解决?

1 个答案:

答案 0 :(得分:1)

您明确创建list traindata

traindata = list(np.array(p.read_table('train.tsv'))[:,2])
          # ^ here

如果您想将其用作numpy.array,请移除list()来电:

traindata = np.array(p.read_table('train.tsv'))[:,2]

其次,您需要shape的{​​{1}},而不是array

data