如何提高python脚本的速度

时间:2014-01-21 23:40:36

标签: python-2.7 csv

我对python很新。我在水文学领域工作,我想学习python来帮助我处理水文数据。

目前我编写了一个脚本来从大数据集中提取信息。我有三个csv文件:

Complete_borelist.csv

Borelist_not_interested.csv

Elevation_info.csv

我想创建一个文件,其中包含complete_borelist.csv中的所有内容,但不包含在borelist_not_interested.csv中。我还想从complete_borelist.csv和Elevation_info.csv获取满足第一个标准的那些钻孔的一些信息。

我的脚本如下:

not_interested_list =[]
outfile1 = open('output.csv','w')
outfile1.write('Station_ID,Name,Easting,Northing,Location_name,Elevation')
outfile1.write('\n')
with open ('Borelist_not_interested.csv','r') as f1:
    for line in f1:
        if not line.startswith('Station'):  #ignore header
            line = line.rstrip()
            words = line.split(',')
            station = words[0]
            not_interested_list.append(station)
with open('Complete_borelist.csv','r') as f2:
    next(f2)   #ignore header
    for line in f2:
        line= line.rstrip()
        words = line.split(',')
        station = words[0]
        if not station in not_interested_list:
            loc_name = words[1]
            easting = words[4]
            northing = words[5]
            outfile1.write(station+','+easting+','+northing+','+loc_name+',')
            with open ('Elevation_info.csv','r') as f3:
                next(f3)    #ignore header
                for line in f3:
                    line = line.rstrip()
                    data = line.split(',')
                    bore_id = data[0]
                        if bore_id == station:
                            elevation = data[4]
                            outfile1.write(elevation)
                            outfile1.write ('\n')                      

outfile1.close()

我对脚本有两个问题:

第一个是Elevation_info.csv没有Complete_borelist.csv中所有孔的信息。当我的循环到达无法找到它的高程记录的工作站时,脚本不会写入“null”,而是继续为同一行中的下一个工作站写入信息。有人可以帮我解决这个问题吗?

第二个是我的完整钻孔列表大约是> 200000行,我的脚本运行速度非常慢。任何人都可以提出让它运行得更快的建议吗?

非常感谢和抱歉,如果我的问题太长了。

1 个答案:

答案 0 :(得分:0)

性能方面,这有几个问题。第一个是您打开并重新读取整个文件的每一行的高程信息。在打开完整文件之前,将高程信息读入键入bore_id的字典中。然后你可以非常快速地测试字典,看看电台是否在其中,而不是重新阅读。

第二个性能问题是,一旦找到匹配项,就不会停止在bore_id列表中搜索。字典的想法也解决了这个问题,但是一旦你有一个匹配就会中断,这会有所帮助。

对于空打印问题,如果bore_id不在字典中,则只需要outfile1.write(“\ n”)。关于字典测试的else语句就是这样做的。在当前代码中,关闭for循环的else会执行此操作。甚至更改最后一次写入的缩进(“\ n”)。