Wade Bratz
Wade Bratz

Reputation: 321

Create Pandas Dataframe with loop

I am trying to create 10 new dataframes from one larger dataframe based on some criteria. See code below.

for i in range(1,11):
    'x_'+str(i) = CRSP_mom[(CRSP_mom['mom_rank'] > (float(i)-1.0)/10)]

I get the error.

  File "<ipython-input-167-902910fdab60>", line 2
    'x_'+str(i) = CRSP_mom[(CRSP_mom['mom_rank'] > (float(i)-1.0)/10) & (CRSP_mom['mom_rank'] <= (float(i))/10)]
SyntaxError: can't assign to operator

Any thoughts on how I could get it to create a dataframe with the looped name?

Thanks much all.

Upvotes: 1

Views: 1034

Answers (1)

Alex
Alex

Reputation: 19104

In general, dynamic variable creation is not a good idea.

How about a dictionary?

d = {'x' + str(i) : CRSP_mom[(CRSP_mom['mom_rank'] > (float(i)-1.0)/10) & (CRSP_mom['mom_rank'] <= (float(i))/10)] for i in range(1, 11)}

Upvotes: 3

Related Questions