gpt4 book ai didi

python - 组合两个for循环以提高效率

转载 作者:太空宇宙 更新时间:2023-11-03 17:02:58 25 4
gpt4 key购买 nike

我通过循环 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'] 进行分组,然后每个循环将只是一个 pdf 文件(并且可能更好地将 与 PdfPages(. ..) 作为 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)

关于python - 组合两个for循环以提高效率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34866643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com