Reputation: 43
I have created a several of dataframes from a larger dataframe using a for loop and dataframe conditions. Here is a snippet of the code below provided df is declared
D_1 = []
for l in range(0,B):
globals()["Final_df_" + str(l)] = df[df.index % B == l].reset_index(drop=True)
But I am not sure exactly how to call them for further computations using a loop again. I have tried different ways
D_1 = ["Final_df_" +str(l)].loc[:,1] #try1
D_1.append(["Final_df_" + str(l)].loc[:,1]) #try2
But I get an error
'list' object has no attribute 'loc'
I am pretty sure it is because of the square parenthesis after str(l) but I am not sure how to call them with out the brackets as D_1 = "Final_df_" + str(l).loc[:,1]
shows an error
'str' object has no attribute 'loc'
I even tried declaring D_1 as a dataframe but still shows error.
Any help would be greatly appreciated. Thanks in advance!
Upvotes: 1
Views: 309
Reputation: 862406
I think using globals for string variables is not good idea, better is create dictionary:
dfs = {}
for l in range(0,B):
dfs["Final_df_" + str(l)] = df[df.index % B == l].reset_index(drop=True)
And then call like:
l = 1
print (dfs["Final_df_" + str(l)])
But if really need it:
l = 1
globals()["Final_df_" + str(l)]
Upvotes: 2