1

I am following a Python for Finance tutorial where you are combining all the S&P500 stocks into one data frame, i. e. outer joining all the stored CSV files for all the different stocks.

current output:sp500

The code for this looks like this:

def compile_data():
with open("sp500tickers.pickle", "rb") as f:
    tickers = Cpickle.load(f)

main_df = pd.DataFrame()

for count, ticker in enumerate(tickers):
    df = pd.read_csv('stock_dfs/{}.csv'.format(ticker))
    df.set_index('Date', inplace=True)

    df.rename(columns={'Adj Close': ticker}, inplace=True)
    df.drop(['Open', 'High', 'Low', 'Close', 'Volume'], 1, inplace=True)

    if main_df.empty:
        main_df = df
    else:
        main_df = main_df.join(df, how='outer')


    if count % 10 == 0:
        print(count)
print(main_df.head())
main_df.to_csv('sp500_joined_closes.csv')

compile_data()

Ideally I would like the data frames to be joined/concatenated like this: Desired output

All ideas and tips are greatly appreciated.

Best regards, Rubrix

3
  • Do you know how to use pivot in Pandas? Commented Nov 2, 2018 at 8:31
  • You can use the df.transpose() method. Commented Nov 2, 2018 at 8:31
  • Not sure how to use pivot in pandas thats why i transformed it in excel Commented Nov 2, 2018 at 9:55

1 Answer 1

3

Use melt like:

pd.melt(df, id_vars=['Date'], var_name='Ticker', value_name='Closed')
Sign up to request clarification or add additional context in comments.

3 Comments

So would it be like this then ? main_df = main_df.melt(df, id_vars='Date', var_name='Ticker', value_name='Closed') instead of: main_df = main_df.join(df, how='outer')
TypeError: melt() got multiple values for argument 'id_vars'
The new code: codeshare.io/amDv7o Gives me this error: new = arr[tuple(slobj)] MemoryError

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.