包含for循环的Python函数仅返回最后一个结果

时间:2018-09-03 12:01:48

标签: python pandas function for-loop plot

在python中使用pandas模块进行数据分析时,我试图创建一个函数,该函数可以将以下过程应用于数据帧列表。 (注意:from plone.app.contentrules.handlers import close for email in emails: evt = SendNotificationEvent(obj, email) notify(evt) close(evt) # make sure it will work for multiple notify( 是我要分析的数据帧之一。)

P1_Assessment

因此,为了分析一个代码块中的数据帧列表,我尝试创建一个函数,如下所示:

P1_Assessment[P1_Assessment > 1].sum(axis=0).astype(int).sort_values(ascending = False).plot(kind = 'bar')`

但是当我在数据帧列表上使用该函数时,仅返回最后一个数据帧的分析结果。 The picture of output from the console is attached here for clarity

我尝试搜索关于stackoverflow的类似主题,但是没有发现任何问题,也许我错过了。任何帮助都将不胜感激!

2 个答案:

答案 0 :(得分:0)

您的问题是,绘图会创建一个绘图,但是当您在循环中再次调用它时,它将覆盖之前的一个绘图调用。因此,您要做的是将每个图保存在列表中或其他内容中,或使用以下命令将它们另存为文件:

 p = a.plot()
 fig = p[0].get_figure()
 fig.savefig("filename.png")

检出Tensorboard中的savefigDataFrame.plot修改

答案 1 :(得分:0)

我列出了两个选项。

第一个选择是在一个图中绘制所有数据框:

def assess_rep(dataframe_list):
    for df in dataframe_list:
        a = df[df > 1].sum(axis= 0).astype(int).sort_values(ascending = False)
        ax = a.plot(kind = 'bar')
return ax

您可以通过以下方式将图形另存为png文件:

ax = assess_rep(dataframe_list)
ax.get_figure().savefig('all_dataframe.png')

第二个选项是将每个数据帧分别绘制并在此过程中保存图形:

import matplotlib.pyplot as plt
def asses_rep(dataframe_list):
    ax_list = []
    counter = 1
    for df in dataframe_list:
        print(counter)
        fig = plt.figure(counter)
        a = df[df > 1].sum(axis= 0).astype(int).sort_values(ascending = False)
        ax = a.plot(kind='bar', fig=fig)
        ax_list.append(ax)
        ax.get_figure().savefig('single_df_%i.png'%counter)
        counter += 1
    return ax_list
相关问题