簡體   English   中英

組合兩個for循環以提高效率

[英]Combining two for loops to improve efficiency

我通過循環csv文件來制作一堆圖,然后基於groupby制作多個圖。 代碼如下:

import pandas as pd   
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages


frame=pd.read_csv('C:\\')

pdf_files = {}
for group_name, group in frame.groupby(['Allotment','Year','Month','Day']):
    allotment,year,month,day = group_name
    if month not in pdf_files:
        pdf_files[allotment,month] = PdfPages(r'F:\Sheyenne\Statistics\IDL_stats\Allotment_histos\Month\SWIR32' + '_' + allotment + '_'+ month + '.pdf') 
    plot=group.plot(x='Percent', y='SWIR32', title=str(group_name)).get_figure()
    pdf_files[allotment,month].savefig(plot)
    plt.close(plot)

for key in pdf_files:
    pdf_files[key].close()

print "Done"  

但這返回一個錯誤,指出打開的文件太多。 我認為如果可以將兩個for循環組合為一個,則可以解決此問題,但是我不確定如何做到這一點。

您首先無法按['allotment', 'month']分組的任何原因['allotment', 'month']然后每個循環將只是一個pdf文件(最好with PdfPages(...) as pdf_file:

basename = r'F:\Sheyenne\Statistics\IDL_stats\Allotment_histos\Month\SWIR32'
for file_name, file in frame.groupby(['Allotment','Month']):
    allotment, month = file_name
    with PdfPages('{}_{}_{}.pdf'.format(basename, allotment, month)) as pdf_file:
        for group_name, group in file.groupby(['Allotment','Month','Year', 'Day']):
            plot = group.plot(x='Percent', y='SWIR32', title=str(group_name)).get_figure()
            pdf_file.savefig(plot)
            plt.close(plot)

這行得通嗎?

import pandas as pd   
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

frame=pd.read_csv('C:\\')

pdf_files = {}
for group_name, group in frame.groupby(['Allotment','Year','Month','Day']):
    allotment,year,month,day = group_name
    if month not in pdf_files:
        pdf_files[allotment,month] = PdfPages(r'F:\Sheyenne\Statistics\IDL_stats\Allotment_histos\Month\SWIR32' + '_' + allotment + '_'+ month + '.pdf') 
    plot=group.plot(x='Percent', y='SWIR32', title=str(group_name)).get_figure()
    pdf_files[allotment,month].savefig(plot)
    pdf_files[allotment,month].close()
    plt.close(plot)

print "Done"  

基本上,只需確保在完成編輯后關閉文件即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM