我目前正在使用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中有没有内置库或技术可以帮助优化这个嵌套循环?

推荐答案

要获得某些列值重复的行,可以使用groupby并排除长度为1的组.

import pandas as pd
df = pd.DataFrame({'val':[1,2,1,2,3,3,4],'data':['A','B','C','D','E','F','G']})
groups = df.groupby('val', sort=False)
results = []
for group in groups:
  if len(group[1]) != 1:
    results.extend(group[1].index[:-1])
print(results)
[0, 1, 4]

纯Python的速度更快的版本如下:

from collections import defaultdict
data = [1,2,1,2,3,3,4]
matching_pairs = []
groups = defaultdict(list)
for i in range(len(data)):
    groups[data[i]].append(i)
for group in groups.values():
    if len(group) != 1:
        matching_pairs.extend(group[:-1])
print(matching_pairs)

包含100万个条目的列表的计时,重复次数为3.

time pandas groupby = 9.831918954849243 seconds
time python groupby = 0.6703155040740967 seconds

纯Python 版本的速度更快,因为Pandas 版本将所有时间都浪费在从Python 对象到Pandas 再到Python的转换上,如果Pandas 完成从文件读取到分组再到写入的所有繁重任务,速度会更快.

Python相关问答推荐

获取2个字节之间的异或

查找3D数组中沿一个轴的相同值序列的长度(与行程长度编码相关)

当变量也可以是无或真时,判断是否为假

是否有方法将现有的X-Y图转换为X-Y-Y1图(以重新填充)?

替换字符串中的点/逗号,以便可以将其转换为浮动

遵循轮廓中对象方向的计算线

Pydantic:如何将对象列表表示为dict(将列表序列化为dict)

根据网格和相机参数渲染深度

非常奇怪:tzLocal.get_Localzone()基于python3别名的不同输出?

运行总计基于多列pandas的分组和总和

在Pandas DataFrame操作中用链接替换'方法的更有效方法

我如何使法国在 map 中完全透明的代码?

Python,Fitting into a System of Equations

索引到 torch 张量,沿轴具有可变长度索引

如何在Python中使用Pandas将R s Tukey s HSD表转换为相关矩阵''

从列表中获取n个元素,其中list [i][0]== value''

搜索按钮不工作,Python tkinter

Python—压缩叶 map html作为邮箱附件并通过sendgrid发送

为什么调用函数的值和次数不同,递归在代码中是如何工作的?

如何将数据帧中的timedelta转换为datetime