简体   繁体   中英

Append Pandas Dataframes in a Loop Function _ Investpy

I am using investpy to get historical stock data for 2 stocks ( TRP_pb, TRP_pc )

import investpy
import pandas as pd
import numpy as np

TRP_pb = investpy.get_stock_historical_data(stock='TRP_pb',
country='canada',
from_date='01/01/2022',
to_date='01/04/2022')
print(TRP_pb.head())

TRP_pc = investpy.get_stock_historical_data(stock='TRP_pc',
country='canada',
from_date='01/01/2022',
to_date='01/04/2022')
print(TRP_pc.head())

I can append the two tables by using the append method

appendedtable = TRP_pb.append(TRP_pc, ignore_index=False)


What I am trying to do is to use a loop function in order to combine these two tables

Here is what I have tried so far

preferredlist = ['TRP_pb','TRP_pc']

for i in preferredlist:

    new = investpy.get_stock_historical_data(stock=i,
                                        country='canada',
                                        from_date='01/01/2022',
                                        to_date='01/04/2022')
    
    new.append(new, ignore_index=True)

However this doesnt work.

I would appreciate any help

Since get_stock_historical_data returns a DataFrame , you can create an empty dataframe before the for loop and concat in the loop.

preferredlist = ['TRP_pb','TRP_pc']

final_list = pd.DataFrame()
for i in preferredlist:
    new = investpy.get_stock_historical_data(stock=i,
                                        country='canada',
                                        from_date='01/01/2022',
                                        to_date='01/04/2022')
    
    final_list = pd.concat([final_list, new])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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