Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

python - How do I create dynamic variable names inside a loop in pandas

I have a dataframe like

month  dest
1       a
1       bb
2       cc 
2       dd
3       ee
4       bb

I need to create a set to 4 another dataframe. I am looping over and hope to assign name of dataframe dynamicall inside loop, like

i=1
while i<=4:

    dataframe+str(i)=org_dataframe.loc[org_dataframe['month'] == i]
    i=i+1

It gives me,

SyntaxError: can't assign to operator

how do I create a dynamic string variable/name of dataframe.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think the best is create dict of objects - see How do I create a variable number of variables?

You can use dict of DataFrames by converting groupby object to dict:

d = dict(tuple(df.groupby('month')))
print (d)
{1:    month dest
0      1    a
1      1   bb, 2:    month dest
2      2   cc
3      2   dd, 3:    month dest
4      3   ee, 4:    month dest
5      4   bb}

print (d[1])
   month dest
0      1    a
1      1   bb

Another solution:

for i, x in df.groupby('month'):
    globals()['dataframe' + str(i)] = x

print (dataframe1)
   month dest
0      1    a
1      1   bb

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...