Home > Blockchain >  How to get the variable name as string from an array of variables?
How to get the variable name as string from an array of variables?

Time:12-06

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?

CodePudding user response:

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.

CodePudding user response:

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

def get_var_name(variable):
     for name in globals():
        if eval(name) is variable:
            return name

a = [df1, df2, df3]

b = [get_var_name(el) for el in a]
# print(b) gives ['df1', 'df2', 'df3']

CodePudding user response:

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.

  • Related