简体   繁体   中英

How to execute a code for within a loop python

Hi I am trying to repeat same code for n times,but without error the below 'for loop' is excuting for only one time
Need to run from reading input file to saving the output file for n times with in loop
Here is the python code that i am trying to run

for i in range(4):
     input_1   = pd.read_csv('D:/input_1.txt',sep='\t')
     input_pivot =  input_1.pivot_table (index = ['Year','Month'] ,columns=['Gender'], 
                                        aggfunc={
                                                 'Tatal_sales':'sum',
                                                 'Tatal_sprofit':'mean' })                                              
                                                 
     input_pivot.to_csv('D:/Output.txt', sep='\t', index=False)

Just need to run above same code for 4 times
Any modifications required?
Thanks in advance

You repeat the same piece of code 4 times, since you do not use the changing variable i .

If you would run the following code, you will get 4 different files:

  1. Output0.txt
  2. Output1.txt
  3. Output2.txt
  4. Output3.txt
    for i in range(4):
         input_1   = pd.read_csv('D:/input_1.txt',sep='\t')
         input_pivot =  input_1.pivot_table(
             index = ['Year','Month'],
             columns=['Gender'], 
             aggfunc={
                 'Total_sales':'sum',
                 'Total_profit':'mean'
             }
         )                                              
                                                     
         input_pivot.to_csv(f'D:/Output{i}.txt', sep='\t', index=False)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM