Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么不能使用For循环语句将数据输入到数据帧中?_Python_Pandas_Dataframe - Fatal编程技术网

Python 为什么不能使用For循环语句将数据输入到数据帧中?

Python 为什么不能使用For循环语句将数据输入到数据帧中?,python,pandas,dataframe,Python,Pandas,Dataframe,当我执行它时,我得到: import pandas as pd import numpy as np def initialize(account): stockList=get_all_securities('stock').index log.info(stockList) sortStocks=pd.DataFrame(columns=['code','price']) for myStock in stockList: priceH

当我执行它时,我得到:

import pandas as pd 
import numpy  as np 
def initialize(account):
    stockList=get_all_securities('stock').index 
    log.info(stockList)
    sortStocks=pd.DataFrame(columns=['code','price'])
    for myStock in stockList:
        priceHistory=history(myStock, ['close'], 1000, '1d', False, 'pre' )
        current_to_median_ratio=priceHistory['close'][0]/np.median(priceHistory['close'])
        sortStocks['code']=myStock
        sortStocks['price']=current_to_median_ratio

    log.info(sortStocks())
SortStock最后是空的,为什么?

使用并尝试以下方法:

2017-09-30 00:00:00 - INFOIndex(['000001.SZ', '000002.SZ', '000004.SZ', '000005.SZ', '000006.SZ',
       '000007.SZ', '000008.SZ', '000009.SZ', '000010.SZ', '000011.SZ',
       ...
       '603987.SH', '603988.SH', '603989.SH', '603990.SH', '603991.SH',
       '603993.SH', '603996.SH', '603997.SH', '603998.SH', '603999.SH'],
      dtype='object', length=3381)
2017-09-30 00:00:00 - INFO<class 'pandas.core.frame.DataFrame'>
2017-09-30 00:00:00 - INFOEmpty DataFrame
Columns: [code, price]
Index: []

这段代码是否应该向sortStocks df添加行?sortStocks['code']=myStock不会这样做,它会将名为code的列中的所有行设置为myStock的值。但是,因为没有行,所以不会发生任何事情
def initialize():
    stockList=get_all_securities('stock').index 
    log.info(stockList)
    sortStocks=pd.DataFrame(columns=['code','price'])
    log.info(type(sortStocks))

    # enumerate list so that you get an index
    for idx, myStock in enumerate(stockList):
        priceHistory=history(myStock, ['close'], 1000, '1d', False, 'pre' )
        current_to_median_ratio=priceHistory['close'][0]/np.median(priceHistory['close'])

        # use .loc to index a row
        sortStocks.loc[idx, 'code'] = myStock
        sortStocks.loc[idx, 'price'] = current_to_median_ratio