-1

I have array of dataframes:

a=[df1,df2,df3]

But I need the variable name as a string

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

How can I do this?

vgb_backup
  • 49
  • 1
  • 6

3 Answers3

1

Taking inspiration from this answer, you can solve your problem with the following code:

def get_var_name(variable):
     for name, value in globals().items():
        if value is variable:
            return name

a = [df1, df2, df3]

b = [get_var_name(el) for el in a]
# print(b) gives ['df1', 'df2', 'df3']
  • This only works if the data frames are globals. It's also inefficient, calling `eval(name)` instead of iterating over `globals().items()` and constructing `len(a)` identical new lists. If it works for you, it works for you, but it's good to keep in mind should you want to do something like this for longer lists! – Jasmijn Dec 06 '21 at 11:57
  • 1
    @Jasmijn I corrected my code, using your suggestions. – Stefano Fiorucci - anakin87 Dec 06 '21 at 13:37
1

It is actually quite tricky to get variable name of an object in python. name->object mapping is strictly one-way. What makes it worse, multiple names can refer to the same object (same chunk of data at a memory address).

However, it is not impossible. Although this method is quite dirty (when there are multiple names referring to the same object.)

Suppose your list a, your dataframe df1, df2, df2 are all global variables, then they are all in globals(). You can try the following one-liner code:

[i for i in globals().keys() if id(eval(i)) in [id(j) for j in a]]

You can verify it yourself.

  • This only works if the data frames are globals. It's also inefficient, calling `eval(i)` instead of iterating over `globals().items()` and constructing `len(a)` identical new lists. If it works for you, it works for you, but it's good to keep in mind should you want to do something like this for longer lists! – Jasmijn Dec 06 '21 at 11:56
  • 1
    Agree. I mean trying to get variable name is somewhat a dirty task. – Sullivan Zheng Jan 01 '22 at 04:03
0

You may use a list comprehension:

a = [df1, df2, df3]
b = [x.name for x in a]

This answer assumes that the names of the data frame variables matches the variable names themselves.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360