简体   繁体   English

如何在 for 循环中通过 for 循环将列表附加到数据帧

[英]How can i append a list to a dataframe via for loop in a for loop

I have made a for loop which uses a list of stock tickers to get day closing prices.我做了一个 for 循环,它使用股票行情列表来获取日收盘价。 Once collected, I ask the code to store the data in a dataframe.收集后,我要求代码将数据存储在数据帧中。 This works fine, but I am having trouble creating a way to append the dataframe over and over again, such that I am left with one large dataframe.这工作正常,但我无法创建一种一遍又一遍地附加数据帧的方法,因此我只剩下一个大数据帧。 Can anybody help with that?有人可以帮忙吗? Please note that the API connection allows a certain amount of calls pr.请注意,API 连接允许一定数量的调用 pr。 minutes and so there should be a time-extension if the call fails - I have tried to account for this.分钟,所以如果通话失败,应该有一个时间延长 - 我试图解释这一点。 Please see code below:请看下面的代码:

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

df = pd.DataFrame() df = pd.DataFrame()

def getdata(symbol_input): 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))打印(获取数据(C20))

You can use pd.concat and then joining everything by using temporary dataframe into one final dataframe.您可以使用 pd.concat 然后通过使用临时数据帧将所有内容连接到一个最终数据帧中。

You can use this code as an example for concatenating two different dataframes into a single final dataframe.您可以使用此代码作为将两个不同的数据帧连接成单个最终数据帧的示例。

dataset1 = pd.DataFrame([[1,2],[2,3],[3,4]],columns=['A','B'])
dataset2 = pd.DataFrame([[4,5],[5,6],[6,7]],columns=['A','B'])
full_dataset = pd.concat([dataset1,dataset2])
full_dataset
   A  B
0  1  2
1  2  3
2  3  4
0  4  5
1  5  6
2  6  7

Reference: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html参考: https : //pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html

Let me know if you require anything else.如果您需要其他任何东西,请告诉我。 Have a great day!祝你有美好的一天!

暂无
暂无

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

相关问题 我怎样才能将 append 这个 for 循环到这个 DataFrame 中? - How can I append this for loop into this DataFrame? 如何在循环结束时将 for 循环和 append 项目运行到列表中? - How can I run a for loop and append items to a list at the end of the loop? 如何在 Python 的循环中将数据帧/数据帧长度附加到列表中 - How do I append dataframes/ lenghts of dataframe to a list in a loop in Python 尝试将 append 添加到列表时,如何使我的 pandas DataFrame 循环更有效率 - How can I make my pandas DataFrame loop more efficient when trying to append to a list 如何使用for循环从Pandas DataFrame列进行追加? - How can I use a for loop to append from a Pandas DataFrame column? 如何将SQL查询循环的结果附加到数据框 - How can I append results from a loop of SQL queries to a dataframe 如何在for循环中将列表正确附加到DataFrame - How to properly append a list to a DataFrame in a for loop 当没有更多项目要附加到列表时,如何打破循环? - How can I break a loop when there are no more items to append to list? 我如何获取两个列表 Pandas DataFrame 列名,并且只使用一个列表,但 append 一个循环中的字符串应用于列名? - How can I take two lists of Pandas DataFrame columns names, and only use one list, but append a string in a loop to be applied to the column name? 无法使用 For 循环将 append 的 Dataframe 的列名添加到列表中 - Can't append Column Names of Dataframe To A List Using For Loop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM