与python open相比,pandas read_csv真的很慢吗?

时间:2016-10-08 16:39:53

标签: python windows python-3.x pandas python-3.5

我的要求是从csv文件中删除重复的行,但文件的大小是11.3GB。所以我替补标记了pandas和python文件生成器。

Python文件生成器:

def fileTestInPy():
    with open(r'D:\my-file.csv') as fp, open(r'D:\mining.csv', 'w') as mg:
        dups = set()
        for i, line in enumerate(fp):
            if i == 0:
                continue
            cols = line.split(',')
            if cols[0] in dups:
                continue
            dups.add(cols[0])
            mg.write(line)
            mg.write('\n')

Python File Generator

使用Pandas read_csv:

import pandas as pd
df = pd.read_csv(r'D:\my-file.csv', sep=',', iterator=True, chunksize=1024*128)
def fileInPandas():
    for d in df:
        d_clean = d.drop_duplicates('NPI')
        d_clean.to_csv(r'D:\mining1.csv', mode='a')

Pandas read_csv

详细信息: 大小:11.3 GB 行:1亿,但在这5000万是重复 Python版本:3.5.2 熊猫版本:0.19.0 内存:8GB CPU:Core-i5 2.60GHz

我在这里观察到的是,当我使用python文件生成器时,我获得了643秒,但是当我使用pandas时,它已经花了1756。

当我使用python文件生成器时,甚至我的系统都没有被挂起,但是当我使用pandas时,我的系统被挂起了。

我在大熊猫中使用正确的方法吗? 即使我想对11.3GB文件进行排序,该怎么做?

1 个答案:

答案 0 :(得分:2)

Pandas不是这项任务的好选择。它将整个11.3G文件读入内存,并对所有列进行字符串到int的转换。我的机器陷入困境并不奇怪!

逐行版本更精简。它不进行任何转换,不会查看不重要的列,也不会在内存中保留大型数据集。这是工作的更好工具。

def fileTestInPy():
    with open(r'D:\my-file.csv') as fp, open(r'D:\mining.csv', 'w') as mg:
        dups = set()
        next(fp) # <-- advance fp so you don't need to check each line
                 # or use enumerate
        for line in fp:
            col = line.split(',', 1)[0]  # <-- only split what you need
            if col in dups:
                continue
            dups.add(col)
            mg.write(line)
            # mg.write('\n')  # <-- line still has its \n, did you
                              # want another?

此外,如果这是python 3.x并且您知道您的文件是ascii或UTF-8,则可以以二进制模式打开这两个文件并保存转换。