0

I want to create multiple empty pd.DataFrame and I thought I can do it with a loop like this:

for share in tickers:
    share=pd.DataFrame()

with:

tickers=['AAPL', 'MSFT', '^GSPC', 'VNA.DE', '^GDAXI', 'HJUE.HA', 'GYC.DE', '2B7K.DE']

But this creates a empty DataFrame named "share" and not 8 different Dataframe named like AAPL, MSFT,...

1 Answer 1

1

It is not recommended, better is create dictionary of DataFrames:

dfs = {x: pd.DataFrame() for x in tickers}

print (dfs)
{'AAPL': Empty DataFrame
Columns: []
Index: [], 'MSFT': Empty DataFrame
Columns: []
Index: [], '^GSPC': Empty DataFrame
Columns: []
Index: [], 'VNA.DE': Empty DataFrame
Columns: []
Index: [], '^GDAXI': Empty DataFrame
Columns: []
Index: [], 'HJUE.HA': Empty DataFrame
Columns: []
Index: [], 'GYC.DE': Empty DataFrame
Columns: []
Index: [], '2B7K.DE': Empty DataFrame
Columns: []
Index: []}

And then select by keys:

print (dfs['AAPL'])
Empty DataFrame
Columns: []
Index: []
Sign up to request clarification or add additional context in comments.

3 Comments

@Ch3steR - hmm, I try dfs['AAPL'] = dfs['AAPL'].assign(a= 1) and not changed all DataFrames, how do you think inplace change?
No problem. defaultdict(pd.DataFrame) is another alternative.+1
but if I try to fill the DataFrames with different content for example with shares[tickers[0]]['Adj Close']=hist_data['Adj Close_AAPL'] all DataFrames in this dict will be filled with the data. not just the first one

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.