[英]Is pandas read_csv really slow compared to python open?
我的要求是从csv文件中删除重复的行,但是文件的大小为11.3GB。 所以我在长凳上标记了熊猫和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')
使用熊猫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')
详细信息:大小:11.3 GB行:1亿,但其中有5000万是重复的Python版本:3.5.2 Pandas版本:0.19.0 RAM:8GB CPU:Core-i5 2.60GHz
我在这里观察到的是,当我使用python文件生成器时花费了643秒,而当我使用熊猫时花费了1756秒。
当我使用python文件生成器时,即使我的系统也没有被挂起,但是当我使用熊猫时,我的系统被挂起了。
我在大熊猫中使用正确的方法吗? 即使我想对11.3GB的文件进行排序,该怎么做?
熊猫不是执行此任务的理想选择。 它将整个11.3G文件读入内存,并对所有列进行字符串到整数的转换。 我对您的机器陷入困境并不感到惊讶!
逐行版本更精简。 它不会进行任何转换,不会打扰不重要的列,也不会在内存中保留大量数据集。 这是工作的更好工具。
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,则可以以二进制模式打开两个文件并保存转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.