[英]How to reduce time for a python program?
我有兩個文件。 文件 1 有 600 萬個條目,34 列,大小為 1.9GB,文件 2 有 500 萬個,16 列,大小為 950 MB。 我必須逐行比較幾列。 我正在使用 csv.DictReader 打開和存儲文件。 我正在使用函數來檢查特定列中的值。 這需要大量時間。 有什么辦法可以縮短時間嗎? 就像我應該使用單個 for 循環和 if 語句而不是多個函數嗎?
import csv
def tsv_to_dict(filename):
with open(filename,'rb') as tsvfile:
data = list(csv.DictReader(tsvfile, delimiter = '\t'))
return data
original_file = tsv_to_dict('original.tsv')
processed_file = tsv_to_dict('processed.tsv')
我使用的功能有以下幾種:
def validate_class_id():
for entry in processed_file:
for item in original_file:
if item['section_ID'] == entry['sID']:
if not item['class ID'] == entry['cID']:
print("Invalid class ID in processed file")
validate_class_id()
我正在使用 5 個這樣的功能。
使用 numpy.where() 和 pandas 之類的東西會更好。
import pandas as pd
import numpy as np
data1 = pd.read_csv('pathtofile1')
data2 = pd.read_csv('pathtofile2')
match = np.where(data1[section_ID].values == data2['sID'].values)
匹配現在將是 sID 相同的索引列表。
np.where() 是矢量化操作。 矢量化操作比循環快得多 - 請查看此鏈接以幫助您學習: https://engineering.upside.com/a-beginners-guide-to-optimizing-pandas-code-for-speed-c09ef2c6a4d6
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.