1

I would like to create 3 dataframes as follows:

basket = [['Apple', 'Banana', 'Orange']]

for fruit in basket:
    fruit = pd.DataFrame(np.random.rand(10,3))

However, after running this, running something like:

Apple

Gives the error

NameError: name 'Apple is not defined

But 'fruit' as a dataframe does work.

How is it possible to have each dataframe produced take a variable as its name?

1
  • I would suggest a dict over variables. Commented Oct 30, 2017 at 14:52

2 Answers 2

4

This would work:

basket = ['Apple', 'Banana', 'Orange']
for fruit in basket:
    vars()[fruit] = pd.DataFrame(np.random.rand(10,3))

However it would be better practice to perhaps assign to a dictionary e.g.:

var_dict={}
basket = ['Apple', 'Banana', 'Orange']
for fruit in basket:
    var_dict[fruit] = pd.DataFrame(np.random.rand(10,3))
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, this is helpful and something I wasn't aware of. How would you then call the dataframe from just the fruit name (i.e. Apple), as I see the only way this way is just via var_dict['Apple']?
the first solution I gave would let you call directly by name, but the dictionary solution wouldn't
3

Instead of creating variables use dict to store the dfs, its not a good practice to create variables on loop i.e

basket = ['Apple', 'Banana', 'Orange']

d_o_dfs = {x: pd.DataFrame(np.random.rand(10,3)) for x in basket}

Not recommended , but in case you want to store it in a variable then use globals i.e

for i in basket:
    globals()[i] = pd.DataFrame(np.random.rand(10,3))

Output : Banana And d_o_dfs['Banana']

        0         1         2
0  0.822190  0.115136  0.807569
1  0.698041  0.936516  0.438414
2  0.184000  0.772022  0.006315
3  0.684076  0.988414  0.991671
4  0.017289  0.560416  0.349688
5  0.379464  0.642631  0.373243
6  0.956938  0.485344  0.276470
7  0.910433  0.062117  0.670629
8  0.507549  0.393622  0.003585
9  0.878740  0.209498  0.498594

Comments

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.