简体   繁体   English

为“ for”循环的每次迭代创建新的df列

[英]Creating new df columns for each iteration of “for” loop

I am trying to calculate the diff_chg of S&P sectors for 4 different dates (given in start_return) : 我正在尝试计算4个不同日期(在start_return中给出)的标准普尔行业的diff_chg:

start_return = [-30,-91,-182,-365]
for date in start_return:
    diff_chg = closingprices[-1].divide(closingprices[date]) 
    for i in sectors:                                  #Sectors is XLK, XLY , etc                                                          
        diff_chg[i] = diff_chg[sectordict[i]].mean()    #finds the % chg of all sectors
        diff_df = diff_chg.to_frame

My expected output is to have 4 columns in the df, each one with the returns of each sector for the given period (-30,-91, -182,-365.) . 我的预期输出是在df中有4列,每列具有给定时间段(-30,-91,-182,-365。)的每个部门的收益。

As of now when I run this code, it returns the sum of the returns of all 4 periods in the diff_df. 截至目前,当我运行此代码时,它将在diff_df中返回所有4个周期的收益之和。 I would like it to create a new column in the df for each period. 我希望它在每个周期的df中创建一个新列。

my code returns: 我的代码返回:

XLK     1.859907
XLI     1.477272
XLF     1.603589
XLE     1.415377
XLB     1.526237

but I want it to return: 但我希望它返回:

        1mo (-30)        3mo (-61)         6mo (-182)         1yr (-365
XLK     1.086547         values here       etc               etc
XLI     1.0334
XLF     1.07342
XLE     .97829
XLB     1.0281

Try something like this: 尝试这样的事情:

start_return = [-30,-91,-182,-365]
diff_chg = pd.DataFrame()
for date in start_return:
    diff_chg[date] = closingprices[-1].divide(closingprices[date])

What this does is to add columns for each date in start_return to a single DataFrame created at the beginning. 这样做是将date in start_return每个date in start_return列添加到DataFrame创建的单个DataFrame

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

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