2

我习惯了 R,它提供了逐列读取 CSV 文件的快速功能,任何人都可以提出一种快速有效的方法来读取 python 中的大数据(例如 CSV)文件吗?例如 CSV 文件的第i列。

我有以下但需要时间:

    import os,csv, numpy, scipy
    from numpy import *
    f= open('some.csv', 'rb') 
    reader = csv.reader(f, delimiter=',')
    header = reader.next()
    zipped = zip(*reader)
    print( zipped[0] ) # is the first column

有没有更好的方法在 python 中读取数据(从大文件中)(至少在内存方面和 R 一样快)?

4

2 回答 2

5

你也可以使用pandas.read_csv和它的use_cols参数。看这里

import pandas as pd

data = pd.read_csv('some.csv', use_cols = ['col_1', 'col_2', 'col_4'])
...
于 2013-05-31T18:35:26.850 回答
2
import csv

with open('some.csv') as fin:
    reader = csv.reader(fin)
    first_col = [row[0] for row in reader]

您正在使用zip的是将整个文件加载到内存中,然后将其转置以获取 col. 如果您只想要列值,只需将其包含在列表中即可。

如果你想要多列,那么你可以这样做:

from operator import itemgetter
get_cols = itemgetter(1, 3, 5)
cols = map(get_cols, reader)
于 2013-05-31T18:26:15.450 回答