首页 > 解决方案 > 有没有更好的方法来加快 Pandas 读取 csv 文件的速度?

问题描述

操作系统:macOS High Sierra,版本 10.13.1 Xcode 中的 Python 3.6

我正在使用 pandas 和传统 python 的 csv 模块读取一个 csv 文件。显然,csv 模块比 pandas 快得多。我知道 pandas 会进行 NaN 检查,但我有两个问题:(i)有没有办法加快 pandas 的速度?(ii) 在 pandas 上使用 python 的 csv 模块有缺点吗?

我的代码:

def read_pd():
    path=os.getcwd()
    filename="Sen_01_sample.csv"
    filePathname=path +"/"+filename
    #print('reading...')
    data=pd.read_csv(filePathname,nrows=11,engine="c",skiprows=0)
    #print('read')

def read_csv():
    path=os.getcwd()
    filename="Sen_01_sample.csv"
    filePathname=path+"/"+filename
    with open(filePathname,mode='r') as csvfile:
        csvread=csv.reader(csvfile)
        col_count=len(next(csvread))
        row_count = sum(1 for row in csvread)
        #print(row_count)

        #print(col_count)
        csvfile.seek(0)
        data=np.zeros((row_count-1,col_count-5),dtype=np.float32)
        row=0
        line_count=0
        for rows in csvread:
            if line_count ==0:
                dummy=0
            else:
                data[row]=np.array(rows[4:-1],dtype=np.float32)
                #print (data[row][-1])
            line_count+=1

计时结果:

Time to read a csv file from Pandas 130.997ms.
Time to read a csv file using Python's native csv module 15.448ms.
Python csv module reads file at 11.79% of the time taken by Pandas.

标签: pythonpandasperformancecsv

解决方案


推荐阅读