快速遍历CSV行的方法?

时间:2020-04-24 01:56:41

标签: python numpy csv

我有一个CSV文件,大约有28,000行x 785列。我需要1)。分离出列header,2)将每行的第一列放入labels数组中,然后3)。将每行的其余784列转换为28x28矩阵,并将其值转换为float后将其附加到我的images数组中。

是否有更快的方法来遍历我的CSV?

    images = np.array([])
    labels = np.array([])

    with open(filename) as training_file:
        reader = csv.reader(training_file, delimiter=',')
        header = np.array(next(reader))

        for row in reader:
            label = row[0] # get each row's label

            pixels = row[1:785] # get pixel values of each row
            pixels = np.array(pixels).astype(float) # transform pixel values to floats
            pixels = pixels.reshape(28,28) # turn into 28x28 matrix

            labels = np.append(labels, np.array(label)) # append to labels array
            images = np.append(images, np.array(pixels)) # append to images array

4 个答案:

答案 0 :(得分:1)

您将使用pandas来读取csv文件。

import pandas as pd
csv_file = pd.read_csv('file.csv')

csv_file.name可以访问列。

根据数据大小,您可以按块读取文件:

import pandas as pd
csv_file = pd.read_csv('file.csv', chunksize=1)

无论如何,请阅读pandas documentation,我认为这是最好的出路

答案 1 :(得分:1)

我认为创建数组很昂贵。附加到数组会在后台重新创建它们,而且也很昂贵。您可以一次分配所有内存,例如:

x = np.empty((28000,784))

然后将每一行保存到数组的每一行。更新阵列非常快速且经过高度优化。完成后,可以更改形状x.shape =(28000,28,28)。注意,数组的形状和内存分配在numpy中是断开的,因此重塑数组不会花费任何费用(它只是更新了如何访问值,不会移动值)。这意味着在添加到数组之前没有理由重新调整每一行的形状。

答案 2 :(得分:0)

迭代几乎不需要时间。问题是您正在使用效率极低的方法来创建阵列。

永远不要与numpy.ndarray个对象一起循环

labels = np.append(labels, np.array(label)) # append to labels array
images = np.append(images, np.array(pixels)) # append to images array

相反,列出labelsimages

labels = []
images = []

然后在您的循环中,追加到列表对象(一种高效的操作)

labels.append(np.array(label)) # append to labels list
images.append(np.array(pixels)) # append to images list

然后,最后,在完成循环后,将数组列表转换为数组:

labels = np.array(labels)
images = np.array(images)

请注意,我不确定您期望的最终数组的形状是什么,您可能需要reshape的结果。您的方法将使每个.append的最终数组变平坦,因为您没有指定轴...如果这确实是您想要的,那么labels.ravel()最终会为您提供

答案 3 :(得分:0)

一些人建议:

  • 重新创建数组并不断追加数组在计算上非常昂贵。相反,我一开始就创建了空数组。这使得原本相对快速的计算变得更快了。
    with open(filename) as training_file:
        reader = csv.reader(training_file, delimiter=',')
        header = np.array(next(reader)) # column headers

        row_count = len(list(reader))

        images = np.empty((row_count, 784)) # empty array
        labels = np.empty((row_count,)) # empty array

        for row in reader:
            labels.append(row[0]) # get each row's label
            images.append(row[1:785]) # get pixel values of each row

    labels = labels.astype(float)
    images = images.reshape(-1, 28,28).astype(float)