Skip to content
Advertisement

How can I append the last row on each dataframe

I am trying to use for loop to append the last row into a new dataframe. However, it only can append the last data into the new dataframe. May I know how can I fix it?

The code looks like this:

list_1 = ['A', 'AAPL', 'U']

new_df = pd.DataFrame(columns=['Date', 'High', 'Low','Open','Volume','Adj Close','d_return','30d_return'])

for stock in list_1:
    
    dateToday = datetime.datetime.today().strftime("%Y-%m-%d")

    end = '2021-03-27'
    start = ''

    df = web.DataReader(stock,'yahoo',start,end)[-70:]
    
    df['d_return'] = df['Adj Close'].pct_change()
    df['10d_return'] = df['d_return'][-10:].sum()
    df['Ticker'] = stock
    df.reset_index(inplace=True)
    new_df = df.iloc[[-1]]
    
    new_df.append(blank_df)
    
new_df

Advertisement

Answer

Try change the line:

new_df = df.iloc[[-1]]

to:

blank_df = df.iloc[-1]

Your code is now resetting new_df to a new value in every iteration with the first line above. Hence, only left with the value set in the last iteration after the loop.

Also, you don’t need double square bracket [[-1]] for .iloc. Just use .iloc[-1] should bring you the last row of df.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement