mt1111
mt1111

Reputation: 33

Python creating dataframes with loop

I would like to create numbered data frames from a list of names, as follows:

tickers = [‘IBM US Equity’, ‘AAPL US Equity’]
for num, ticker in enumerate(tickers, start=1):
      df[num] = df.loc[ticker]
      print(df[num])

df is another pandas dataframe with the tickers as it’s index. So writing out the following does indeed give me the desired result:

df1 = df.loc[‘IBM US Equity’]
print(df1)

However, when trying to use the loop I’m getting an error message: “Wrong number of items passed 4, placement implies 1”

What am I missing?

Thanks a lot for your help!

Upvotes: 1

Views: 386

Answers (1)

jpp
jpp

Reputation: 164843

Use a dictionary for a variable number of variables:

tickers = ['IBM US Equity', 'AAPL US Equity']

df_dict = {}

for num, ticker in enumerate(tickers, start=1):
      df_dict[num] = df.loc[ticker]

Then access elements via df_dict[1], etc.

An alternative way to formulate your logic is to use a dictionary comprehension:

df_dict = {num: df.loc[ticker] for num, ticker in enumerate(tickers, 1)}

The reason your code errors is pandas is trying to add a dataframe to a series: the left hand side of df[num] = df.loc[ticker] is a series, while the right hand side is a dataframe. This is not possible and, fairly descriptively, pandas complains about an incorrect number of items.

Upvotes: 1

Related Questions