Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 518
abhinay_k Avatar asked Jul 15 '17 05:07

abhinay_k


People also ask

How do you dynamically declare variables inside a loop in python?

Use the for Loop to Create a Dynamic Variable Name in Python Along with the for loop, the globals() function will also be used in this method. The globals() method in Python provides the output as a dictionary of the current global symbol table.

How do you automatically create a variable in python?

“python automatically create variables” Code Answer'sglobals()[f"my_variable{i}"] = f"Hello from variable number {i}!"


2 Answers

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
like image 97
jezrael Avatar answered Oct 22 '22 00:10

jezrael


You can use a list of dataframes:

dataframe = []
dataframe.append(None)

group = org_dataframe.groupby('month')

for n,g in group:
    dataframe.append(g)

dataframe[1]

Output:

   month dest
0      1    a
1      1   bb

dataframe[2]

Output:

   month dest
2      2   cc
3      2   dd
like image 42
Scott Boston Avatar answered Oct 22 '22 01:10

Scott Boston