1

How do i loop through my excel sheet and add each 'Adjusted Close' to a dataframe? I want to summarize all adj close and make an stock indice.

When i try with the below code the dataframe Percent_Change is empty.

xls = pd.ExcelFile('databas.xlsx')
countSheets = len(xls.sheet_names)

Percent_Change = pd.DataFrame()

x = 0
for x in range(countSheets):
    data = pd.read_excel('databas.xlsx', sheet_name=x, index_col='Date')

    # Calculate the percent change from day to day
    Percent_Change[x] = pd.Series(data['Adj Close'].pct_change()*100,     index=Percent_Change.index)


 stock_index = data['Percent_Change'].cumsum()

1 Answer 1

1

unfortunately I do not have the data to replicate your complete example. However, there appears to be a bug in your code. You are looping over "x" and "x" is a list of integers. You probably want to loop over the sheet names and append them to your DF. If you want to do that your code should be:

import pandas as pd

xls = pd.ExcelFile('databas.xlsx')
# pep8 unto thyself only, it is conventional to use "_" instead of camelCase or to avoid longer names if at all possible
sheets = xls.sheet_names

Percent_Change = pd.DataFrame()

# using sheet instead of x is more "pythonic"
for sheet in sheets:
    data = pd.read_excel('databas.xlsx', sheet_name=sheet, index_col='Date')

    # Calculate the percent change from day to day
    Percent_Change[sheet] = pd.Series(data['Adj Close'].pct_change()*100, index=Percent_Change.index)

stock_index = data['Percent_Change'].cumsum()
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.