1

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!

1 Answer 1

2

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)]
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks for the suggestion on the global(). But I am stuck on calling the dataframe {in this case "Final_df_" + str(l)} using the for loop to perform computations like the one mentioned above (["Final_df_" + str(l)].loc[:,1]).
@AjithViswanath - Hmm, so you need globals()["Final_df_" + str(l)] = globals()["Final_df_" + str(l)].loc[:, 1] ?
Yes. After creating the dataframe 'Final_df_0' (first instance), i want to perform computations on some of the data.
@AjithViswanath - so working for you comment above?
I am able to create the dataframe using the first coding snippet. But I am not sure how to call them to perform computations and store them in D_1. I tried the codes in the second snippet but i get error messages
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.