For循环:使用Pandas将字典迭代输出写入Excel?

时间:2020-03-04 00:24:49

标签: python pandas

我正在尝试遍历其值中包含多个行索引的字典,然后应用pd.nsmallest函数为该字典中的多组行索引生成前3个最小值。但是,我的for循环语句似乎出了点问题,因为我一遍又一遍地覆盖了前3个值,直到字典中的最后一组值为止,所以我的最终excel文件输出仅显示了最后一行的3行for循环。

当我使用print语句时,它可以按预期方式工作,并且我得到了字典中所有16个值的输出,但是当写入excel文件时,它只为我提供了循环中最后一次运行的输出

import pandas as pd
from tabulate import tabulate
VA = pd.read_excel('Columnar BU P&L.xlsx', sheet_name = 'Variance by Co')

legcon = VA[['Expense', 'Consolidation', 'Exp Category']]
legcon['Variance Type'] = ['Unfavorable' if x < 0 else 'favorable' for x in legcon['Consolidation']]

d = {'Travel & Entertainment': [1,2,3,4,5,6,7,8,9,10,11], 'Office supplies & Expenses': [13,14,15,16,17],
'Professional Fees':[19,20,21,22,23], 'Fees & Assessments':[25,26,27], 'IT Expenses':[29],
'Bad Debt Expense':[31],'Miscellaneous expenses': [33,34,35,36,37],'Marketing Expenses':[40,41,42],
'Payroll & Related Expenses': [45,46,47,48,49,50,51,52,53,54,55,56], 'Total Utilities':[59,60],
'Total Equipment Maint, & Rental Expense': [63,64,65,66,67,68],'Total Mill Expense':[70,71,72,73,74,75,76,77],
'Total Taxes':[80,81],'Total Insurance Expense':[83,84,85],'Incentive Compensation':[88],
'Strategic Initiative':[89]}

当我这样做时,直接输出打印效果很好

for key,value in d.items():
    a = legcon.iloc[value][legcon.iloc[:,1]<0].nsmallest(3,'Consolidation')
    print(a)

                Expense  Consolidation            Exp Category Variance Type
5  Transportation - AIR         -19054  Travel & Entertainment   Unfavorable
9                 Meals          -9617  Travel & Entertainment   Unfavorable
7               Lodging          -9439  Travel & Entertainment   Unfavorable

            Expense  Consolidation        Exp Category Variance Type
26     Bank Charges          -4320  Fees & Assessments   Unfavorable
27  Finance Charges          -1389  Fees & Assessments   Unfavorable
25     Payroll Fees          -1145  Fees & Assessments   Unfavorable

但是,当我使用以下代码写入excel时:

writer = pd.ExcelWriter('testt.xlsx', engine = 'xlsxwriter')
row = 0
for key,value in d.items():
    a = legcon.iloc[value][legcon.iloc[:,1]<0].nsmallest(3,'Consolidation')
    for i in range(0,16): 
        a.to_excel(writer, sheet_name = 'test', startrow = row+4, index = False)

writer.save()   

我的输出看起来像这样,并没有显示所有的exp类别: the output of the last iteration of the loop

我非常感谢您提供有关如何更正此问题的反馈。提前致谢!

1 个答案:

答案 0 :(得分:0)

在朋友的帮助下,我刚刚意识到我的愚蠢错误,我的for循环中没有行迭代器供输出在下一行输出,并使用以下代码解决了该问题(最初,我将行迭代器放置在其中我的df.to_excel语句):

writer = pd.ExcelWriter('testt.xlsx', engine = 'xlsxwriter')
row = 0
for key,value in d.items():
    a = legcon.iloc[value][legcon.iloc[:,1]<0].nsmallest(3,'Consolidation')
    a.to_excel(writer, sheet_name = 'Testt', startrow = row, index = False)
    row = row+4
writer.save()