我目前正在使用Python3.8编写一个数据分析脚本,在该脚本中我需要处理一个由100多万行组成的大型数据集.我的脚本使用嵌套循环根据特定条件将每一行与多个其他行进行比较.我注意到性能明显很慢,我怀疑嵌套循环是瓶颈.
以下是代码中有问题的部分的简化版本:
import csv
file_path = 'data.csv'
data = []
with open(file_path, 'r') as file:
reader = csv.reader(file)
for row in reader:
data.append(row)
matching_pairs = [] # List to store the indices of matching row pairs
for i in range(len(data)):
for j in range(i + 1, len(data)):
if data[i][0] == data[j][0]:
# Append the pair of indices to the matching_pairs list
matching_pairs.append(i)
output_file = 'matching_pairs.txt'
with open(output_file, 'w') as file:
for pair in matching_pairs:
file.write(f'{pair}\n')
内部循环将当前行与所有后续行进行比较,这对我的分析非常重要.然而,我预计处理过程会更快.我正在寻找一种方法来优化这部分代码,以减少执行时间.
我可以采用什么策略来提高如此密集的Python操作的性能呢?在Python中有没有内置库或技术可以帮助优化这个嵌套循环?