我如何通过for循环中的for循环将列表附加到数据框

问题描述 投票:1回答:1

我创建了一个for循环,该循环使用股票行情清单来获取当日收盘价。收集后,我要求代码将数据存储在数据框中。这可以正常工作,但是我很难创建一种反复添加数据框的方法,以至于我只剩下一个大的数据框。有人可以帮忙吗?请注意,API连接允许一定数量的调用pr。分钟,因此如果通话失败,则应该延长时间-我已尝试解决此问题。请参见下面的代码:

C20 = ['AMBU-B.CPH','MAERSK-B.CPH']

df = pd.DataFrame()

def getdata(symbol_input):

for i in symbol_input:

    try:

        API_KEY = 'XXXXXXXXX' #MY API KEY

        symbol = i #søg på google efter firmanavnet og "stock price". Tickeren er den der skal bruges

        r = requests.get('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=' + i + '&apikey=' + API_KEY)

        result = r.json()
        AllData = result['Time Series (Daily)']
        alldays = list(AllData.keys())
        alldays.sort()
        timeinterval = 10
        days = alldays[len(alldays)-timeinterval:len(alldays)]
        #print(days)

        SymbolList = []
        for i in range(timeinterval):
            SymbolList.append(symbol)
        #print(SymbolList)

        StockPriceList = []


        if (r.status_code == 200):

            for i, day in enumerate(days):
                result = r.json()
                dataForAllDays = result['Time Series (Daily)']
                dataForSingleDate = dataForAllDays[days[i]]
                #print (days[i], dataForSingleDate['4. close']) 
                StockPriceList.append(dataForSingleDate['4. close'])  


        #print(StockPriceList)

        combined_lists = list(zip(days, StockPriceList, SymbolList)) #create tuples to feed into dataframe from multiple lists

        df1 = pd.DataFrame(combined_lists, columns = ['Date', 'Price', 'Stock Ticker'])
        print(df1)

        time.sleep(10)

    except:
        print('could not get data for: ' + i)
        time.sleep(1)  # wait for 1 seconds before trying to fetch the data again
        continue

print(getdata(C20))

python python-3.x dataframe for-loop append
1个回答
1
投票

0
投票
© www.soinside.com 2019 - 2024. All rights reserved.