Home > Net >  Save the Output of for loop of a DataFrame to a DataFrame that is declared outside
Save the Output of for loop of a DataFrame to a DataFrame that is declared outside

Time:05-09

Is there any way to save the output of a dataframe that is evaluated inside a for loop to a data frame that is empty and is declared outside the for loop? Can we save the output of for loop separately for every iteration?

new_dict1 = {'ABW':{'ABR':1,'BPR':1,'CBR':1,'DBR':0},'BCW':{'ABR':0,'BPR':0,'CBR':1,'DBR':0},
        'CBW':{'ABR':1,'BPR':1,'CBR':0,'DBR':0},'MCW':{'ABR':1,'BPR':1,'CBR':0,'DBR':1}}
df = pd.DataFrame.from_dict(new_dict1,orient="index")
df4 = pd.DataFrame()
for i in range(2):
 df3 = df.iloc[0:3, 1:4]
 print(df3)
 #df4.append(df3)

Output Which I have got

         BPR  CBR  DBR
  ABW    1    1    0
  BCW    0    1    0
  CBW    1    0    0
         BPR  CBR  DBR
  ABW    1    1    0
  BCW    0    1    0
  CBW    1    0    0

The output which I have got is the output of two iterations of for loop when it is operated. I want to save the output of every iteration of for loop outside the for loop within another dataframe.

CodePudding user response:

you can concat the dataframes:

import pandas as pd
new_dict1 = {'ABW':{'ABR':1,'BPR':1,'CBR':1,'DBR':0},'BCW':{'ABR':0,'BPR':0,'CBR':1,'DBR':0},
    'CBW':{'ABR':1,'BPR':1,'CBR':0,'DBR':0},'MCW':{'ABR':1,'BPR':1,'CBR':0,'DBR':1}}
df = pd.DataFrame.from_dict(new_dict1,orient="index")
df4 = pd.DataFrame()
for i in range(2):
    df3 = df.iloc[0:3, 1:4]
    df4 = pd.concat([df4, df3])
print(df4)
  • Related