如何运行for循环并在循环结束时将项目追加到列表中?

时间:2020-09-23 22:16:11

标签: python python-3.x

我在这里遗漏了一些非常基本的东西,但这已经是漫长的一天,我不确定会发生什么。在下面的示例中,我将循环遍历列表调用“ tickers”三次。我想将某些分析的结果附加到每个循环末尾的列表中,因此要附加三个,而不是100个以上。这是我的代码。

from pandas_datareader import data as wb
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pylab import rcParams
from sklearn.preprocessing import MinMaxScaler


start = '2020-03-01'
end = '2020-09-22'

tickers = ['TAN','QCLN','PBW']

thelen = len(tickers)

z=0
all_stocks=[]

price_data = []
for ticker in tickers:
    prices = wb.DataReader(ticker, start = start, end = end, data_source='yahoo')[['Open','Adj Close']]
    price_data.append(prices.assign(ticker=ticker)[['ticker', 'Open', 'Adj Close']])

    #names = np.reshape(price_data, (len(price_data), 1))
    
    df = pd.concat(price_data)
    df.reset_index(inplace=True)
    
    # doing some analysis in here, then writing results to a dataframe...

    z=z+1
    print(str(z) + ' of ' + str(thelen))
    
all_stocks.append(ticker + ' act: ' + str(new_seriesdata['Adj Close'].iloc[-1]) + ' prd: ' + str(myclosing_priceresult))

现在,我获得了数据框中最后一个行情自动收录器中的所有项目,但前两个已消失。我需要代码+ str(new_seriesdata ['Adj Close']。iloc [-1]),这是数据框中的最后一项。

2 个答案:

答案 0 :(得分:2)

  • 问题是,代码可能正在对数据帧prices进行就地更新。
    • 这似乎在熊猫1.1.1版中没有发生。
  • 每次循环迭代,prices都会更改
  • price_data = []
    • price_data = [prices, prices, prices]
  • 要正确地附加prices,请使用.copy()
  • df = pd.concat(price_data)不应出现在循环中
  • 如果您随后要对每个股票行情进行计算,请使用df.groupby('ticker')并汇总计算。
price_data = []

for ticker in tickers:
    prices = wb.DataReader(ticker, start = start, end = end, data_source='yahoo')[['Open','Adj Close']]
    price_data.append(prices.assign(ticker=ticker)[['ticker', 'Open', 'Adj Close']].copy())

df = pd.concat(price_data).reset_index()

df.head()

        Date ticker       Open  Adj Close
0 2020-03-02    TAN  36.630001  36.990002
1 2020-03-03    TAN  37.770000  37.130001
2 2020-03-04    TAN  38.130001  38.520000
3 2020-03-05    TAN  37.639999  38.330002
4 2020-03-06    TAN  37.299999  36.880001

df.tail()

          Date ticker       Open  Adj Close
424 2020-09-16    PBW  57.410000  57.650002
425 2020-09-17    PBW  56.130001  56.480000
426 2020-09-18    PBW  57.189999  57.310001
427 2020-09-21    PBW  56.139999  56.639999
428 2020-09-22    PBW  56.580002  56.509998

答案 1 :(得分:1)

当前,您将在循环的最后递归之后追加到all_stocks。要解决此问题,您要做的就是将附加移入for循环中,以便每次循环都被调用。

由于python关心缩进,因此将行移动到循环中所需要做的就是使它缩进:

for ticker in tickers:
    prices = wb.DataReader(ticker, start = start, end = end, data_source='yahoo')[['Open','Adj Close']]
    price_data.append(prices.assign(ticker=ticker)[['ticker', 'Open', 'Adj Close']])

    #names = np.reshape(price_data, (len(price_data), 1))
    
    df = pd.concat(price_data)
    df.reset_index(inplace=True)
    
    # doing some analysis in here, then writing results to a dataframe...

    z=z+1
    print(str(z) + ' of ' + str(thelen))

    # NOTE: Change comes below
    
    all_stocks.append(ticker + ' act: ' + str(new_seriesdata['Adj Close'].iloc[-1]) + ' prd: ' + str(myclosing_priceresult))

别担心,这是一个普遍的问题,每个人都会发生