Home > Software design >  How to save outputs of for loop into a dataframe in Jupyter
How to save outputs of for loop into a dataframe in Jupyter

Time:09-18

I have a for loop as follow:

    Region = ['A', 'B', 'C', 'D', 'E']
    i = 5
    for Region in Region:
            rr = q * s.at[i 1, 'Value'] 
            tt = w * s.at[i 1, 'Value']
            yy = e * s.at[i 1, 'Value']
print(Region, rr, tt, yy)            
i  =1

which its result is like:

A 2 5 3

B 6 2 117

C 23 875 42

D 71 26 125

E 65 24 11

How can I save its outputs in a dataframe?

CodePudding user response:

Try pandas.DataFrame() method from pandas library Ref. If you're new to pandas, check Getting started guide. You will need to create a dictionary, such as:

{"A": {"rr":2, "tt":5, "yy":3}, 
 "B": {"rr":6, "tt":2, "yy":117}}

Constructing dataframe with this dictionary will turn keys A and B into columns and rr, tt and yy into rows. You can always apply pandas.Dataframe.transpose() method to the dataframe object to convert columns into rows and vice-versa Ref

Implementation in your code

import pandas as pd

#create empty dictionary
d={} 

Region = ['A', 'B', 'C', 'D', 'E']
i = 5
for Region in Region:
        rr = q * s.at[i 1, 'Value'] 
        tt = w * s.at[i 1, 'Value']
        yy = e * s.at[i 1, 'Value']
        print(Region, rr, tt, yy)            
        i  =1
        #store data in dictionary
        d[Region] = {"rr":rr, "tt":tt, "yy":yy}

#convert dictionary to dataframe
df = pd.DataFrame(d)

#transpose, if you want
df.transpose()
  • Related