0

I have a list:

list1 = ['brand1','brand2']

I want to create a dataframe such that:

import pandas as pd for i in list1: "df_" + i = pd.read_csv('filepath'+i)

i want to create dataframe as:

df_brand1= (containing dataframe of brand1)

df_brand2= (containing dataframe of brand2)

  • Looks like you need `global` – Rakesh May 23 '18 at 05:04
  • Either hard-code it if it is fixed - or if it is variable then this is what `dict`s are for `data["df_"+i] = pd.read_csv(...)`. – AChampion May 23 '18 at 05:06
  • Even though `dict` can be useful in this case, there is also a way to do what OP asked. `locals()["test"] = "xxx`. This will create a variable named 'test' with the value 'xxx'. I was writing answer half way when the question became closed. – thuyein May 23 '18 at 05:08
  • @ThuYeinTun Yes, while you can do that, it is nearly always a bad idea to do so. – AChampion May 23 '18 at 05:10
  • @AChampion May I ask why it is a bad idea so I can avoid it in the future. – thuyein May 23 '18 at 05:11
  • @AChampion if i use dictionary then what to do when I have to concatenate these two dataframe into new dataframe, when i tried doing it, i got following error.. ``` first argument must be an iterable of pandas objects, you passed an object of type "DataFrame ``` – Aayush Tomar May 23 '18 at 05:31
  • As per documentation: "Note   The contents of this dictionary should not be modified; ...". If you are not in a function locals() will return globals() which does technically work but also a bad idea. – AChampion May 23 '18 at 12:55
  • @AayushTomar, just use a `list` or you can do `dict.values()` and if you need individual args then use `*` expansion syntax. – AChampion May 23 '18 at 12:57

0 Answers0