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,...

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
MikeMike
  • 27
  • 3

1 Answers1

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: []
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • @Ch3steR - hmm, I try `dfs['AAPL'] = dfs['AAPL'].assign(a= 1)` and not changed all DataFrames, how do you think inplace change? – jezrael Jun 19 '20 at 08:16
  • No problem. `defaultdict(pd.DataFrame)` is another alternative.+1 – Ch3steR Jun 19 '20 at 08:25
  • 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 – MikeMike Jun 19 '20 at 09:51