简体   繁体   English

如何在 Jupyter 中将 for 循环的输出保存到 dataframe 中

[英]How to save outputs of for loop into a dataframe in Jupyter

I have a for loop as follow:我有一个for循环如下:

    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一个 2 5 3

B 6 2 117乙 6 2 117

C 23 875 42 C 23 875 42

D 71 26 125电话 71 26 125

E 65 24 11 65 24 11

How can I save its outputs in a dataframe?如何将其输出保存在 dataframe 中?

Try pandas.DataFrame() method from pandas library Ref .尝试 pandas 库参考中的pandas.DataFrame()方法。 If you're new to pandas, check Getting started guide .如果您不熟悉 pandas,请查看入门指南 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.使用此字典构造 dataframe 会将键AB转换为列,并将rrttyy转换为行。 You can always apply pandas.Dataframe.transpose() method to the dataframe object to convert columns into rows and vice-versa Ref您始终可以将pandas.Dataframe.transpose()方法应用于 dataframe ZA8CFDE63311C69EB2ACZReftoB9 列转换为149EB2ACZReftoB9行,反之亦然

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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