0

I have a list of few variable names. I am trying to see if we can have empty Dataframe created for each of these variable names.

sample_list = ['item_1','item_2','item_3']

I want to create an empty Dataframe for each of these 3 items in the list. The structure would be same as well. They would have two columns, namely Product_Name, Quantity.

Expected output:

Dataframe 1 : item_1

Dataframe 2 : item_2

Dataframe 3 : item_3

3 Answers 3

1

IIUC, I would create a dictionary of dataframes using dictionary comprehension:

dict_of_dfs = {k:pd.DataFrame(columns=['Product','Quantity']) for k in sample_list}

Then you can see your dataframes using:

dict_of_dfs['item_1']
dict_of_dfs['item_2']
Sign up to request clarification or add additional context in comments.

Comments

1

Here is the working solution to what you have described.

Create an empty dictionary and think of the items in the list as the keys to access your dictionary. The data against each key is a Pandas DataFrame (empty) and has the two columns as you said.

sample_list = ['l1', 'l2', 'l3']

sample_dict = dict()

for index, item in enumerate(sample_list):
    print('Creating an empty dataframe for the item at index {}'.format(index))
    sample_dict['{}'.format(item)] = pd.DataFrame(columns=['Product_Name', 'Quantity'])

Check if the dictionary got correctly created:

print(sample_dict)

{'l1': Empty DataFrame
 Columns: [Product_Name, Quantity]
 Index: [],
 'l2': Empty DataFrame
 Columns: [Product_Name, Quantity]
 Index: [],
 'l3': Empty DataFrame
 Columns: [Product_Name, Quantity]
 Index: []}

And the keys of the dictionary are indeed the items in the list:

print(sample_dict.keys())
dict_keys(['l1', 'l2', 'l3'])

Cheers!

Comments

0

Intuitivelly I'd create a dict, where the keys are the elements in the list, and the values are the dataframes:

d = {}
for item in sample_list:
    d[item] = pd.DataFrame() # df creation

To access the dfs:

d['item_1']...

4 Comments

thanks for the reply.. I did check this.. If I try run the variable name after running the above code it says NameError: name 'variable_name' is not defined
What'd be "variable_name"?
as mentioned above these are values from the list sample_list = ['item_1','item_2','item_3']
"try run the variable name" What exactly are you running?

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.