如何在循环语句中将数据存储到Dataframe变量中?

时间:2018-10-07 12:56:32

标签: python pandas dataframe

I write:


 sortstocks['stockCode']=myStock
    sortStocks['ratio']=ratio

它不起作用。更多代码如下:

 for idx, myStock in enumerate(stockList):
    close=history(myStock, ['close'], 500, '1d', False, 'pre' )
    if len(close)>499:
       ....

       if (MA10Yesterday < MA20Yesterday) and (MA10today > MA20today) and (MA5today> MA10today) and (MA5today < MA58today):
          for i in range(2,500):
              if ...
                 sortstocks['stockCode']=myStock
                 sortStocks['ratio']=ratio
I'm told that sortstocks is not defined, but I have defined in initialize with sortStocks=pd.DataFrame(columns=['stockCode','ratio']) 

感谢尼尔斯的帮助。现在,我将代码重写为:

             sortStocks.loc[idx,'stockCode']=myStock
             sortStocks.loc[idx,'ratio']=ratio

运行它时,我得到的数据如下:

  0  stockCode     ratio
0     stockCode        NaN       NaN
1         ratio        NaN       NaN
64          NaN  000153.SZ  0.834303
1518        NaN  300171.SZ  0.631573
1774        NaN  300430.SZ  0.662017

我想要这样的输出:

  stockCode     ratio
     000153.SZ  0.834303
     300171.SZ  0.631573
     300430.SZ  0.662017

我该怎么办?

1 个答案:

答案 0 :(得分:1)

如果上面的代码是您运行的代码的正确副本,则错误出在最后三行的错字中:

sortstocks['stockCode']=myStock

应为:

sortStocks['stockCode']=myStock

(..股票以大写字母“ S”表示)