Kevin Nash
Kevin Nash

Reputation: 1561

Pandas - Creating empty Dataframe dynamically for every item in list

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

Upvotes: 0

Views: 604

Answers (3)

Nikhil K.
Nikhil K.

Reputation: 301

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!

Upvotes: 1

89f3a1c
89f3a1c

Reputation: 1488

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']...

Upvotes: 0

Scott Boston
Scott Boston

Reputation: 153500

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']

Upvotes: 1

Related Questions