2

I have a python list of strings that are the names of variables representing dataframes.

my_dataframe_list = ['df1', 'df2', 'df3']

so conceptually, the single quotes need to be removed and the final output should be a list of dataframes.

my_dataframe_list = [df1, df2, df3]
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Prathap Kb
  • 35
  • 5
  • `import ast` then `ast.literal_eval(List)` ? – anky Apr 29 '21 at 19:35
  • They don't seem to want to parse a string list. I think that's a misinterpretation. – Carcigenicate Apr 29 '21 at 19:36
  • @Carcigenicate okay. Should I reopen? Looks unclear still – anky Apr 29 '21 at 19:42
  • 1
    @anky I don't think your dupe is what they're asking, but ya, it's not clear. They don't have quotes around the initial list, so it doesn't seem like the starting data is a string. It seems like they're confused about what the quotes in the printed representation mean. – Carcigenicate Apr 29 '21 at 19:44
  • 1
    I think you want [this](https://stackoverflow.com/questions/44639357/print-python-list-without-quotation-marks-or-space-after-commas) or [this](https://stackoverflow.com/questions/5445970/how-to-properly-print-a-list), then wrap it in `[`/`]`s. – Carcigenicate Apr 29 '21 at 19:47
  • 4
    are `a` `b` and `c` defined variables? – JonSG Apr 29 '21 at 21:26
  • I edited my question. the initial list has quotes for all the items in it which i need to eliminate – Prathap Kb Apr 30 '21 at 06:06

2 Answers2

1

One way is to use the built-in eval() method:

my_dataframe_list = ['df1', 'df2', 'df3']
my_dataframe_list = [eval(df) for df in my_dataframe_list]

Instead of the list comprehension, you can use map():

my_dataframe_list = ['df1', 'df2', 'df3']
my_dataframe_list = list(map(eval, my_dataframe_list))

But beware, the eval method is dangerous; you should never use it on untrusted input. See this article for more details: Eval really is dangerous

Perhaps a more filtered list would be better:

my_dataframe_list = [eval(df) for df in my_dataframe_list if df.startswith('df') and df[2:].isdigit()]

But of course, the best thing you can do is to structure your existing code in a way that doesn't require the use of eval.


This Stack Overflow post suggests the ast.literal_eval() method: Python: make eval safe

Of course, it would require you to install the ast module, and the string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

Red
  • 26,798
  • 7
  • 36
  • 58
1

You can access it from globals() or locals():

df1 = pd.DataFrame([1, 2, 3])
df2 = pd.DataFrame([2, 4, 6])
my_dataframe_list = ['df1', 'df2']

my_dataframe_list = [globals()[df] for df in my_dataframe_list]
my_dataframe_list[0]

#    0
# 0  1
# 1  2
# 2  3
my_dataframe_list[1]

#    0
# 0  2
# 1  4
# 2  6
tdy
  • 36,675
  • 19
  • 86
  • 83