Python-使用DataReader的数据帧的Concat列表

时间:2018-12-24 05:13:48

标签: python pandas dataframe pandas-datareader

我正在尝试使用pandas_datareader捕获库存数据。给定少量的股票代号,只需手动编写每个DataReader调用的脚本,然后合并结果就很容易了。但是,如果列表的长度增加到更多,则必须有一种更简单的方法来迭代该过程。

import pandas_datareader.data as web
import pandas as pd

symbols = ['AMZN','AAPL','MSFT','NFLX','GOOGL']
for i in symbols:
    print(i)

dfAMZN = web.DataReader('AMZN','yahoo')
dfAMZN['Symbol'] = 'AMZN'
dfAMZN['Date'] = dfAMZN.index

dfAAPL = web.DataReader('AAPL','yahoo')
dfAAPL['Symbol'] = 'AAPL'
dfAAPL['Date'] = dfAAPL.index

dfMSFT = web.DataReader('MSFT','yahoo')
dfMSFT['Symbol'] = 'MSFT'
dfMSFT['Date'] = dfMSFT.index

dfNFLX = web.DataReader('NFLX','yahoo')
dfNFLX['Symbol'] = 'NFLX'
dfNFLX['Date'] = dfNFLX.index

dfGOOGL = web.DataReader('GOOGL','yahoo')
dfGOOGL['Symbol'] = 'GOOGL'
dfGOOGL['Date'] = dfGOOGL.index

frames = [dfAMZN, dfAAPL, dfMSFT, dfNFLX, dfGOOGL]
dfStocks = pd.concat(frames)

有没有一种方法可以遍历符号列表并执行以下步骤,而不仅仅是打印i?

1 个答案:

答案 0 :(得分:1)

list comprehensionassign一起用于新列:

symbols = ['AMZN','AAPL','MSFT','NFLX','GOOGL']
frames = [web.DataReader(i,'yahoo').assign(Symbol = i, Date = lambda x: x.index) 
          for i in symbols]

dfStocks = pd.concat(frames)

另一种选择:

symbols = ['AMZN','AAPL','MSFT','NFLX','GOOGL']

frames = []
for i in symbols:
    df = web.DataReader(i,'yahoo')
    df['Symbol'] = i
    df['Date'] = df.index
    frames.append(df)

dfStocks = pd.concat(frames)