VPN
VPN

Reputation: 113

Accessing name of the element from a list of dataframe

I have a list of the dataframes as follows:

dept = [Phy,Chem,Bio,Maths,Social]

Each of the dataframes have huge amount of data. I need to access the name of these dataframes from the list for further use in looping. I tried this code for example:

str(dept[0])

But this is giving me the contents of the dataframe 'Phy'. Where as I need just to print 'Phy'.

Upvotes: 3

Views: 953

Answers (1)

keepAlive
keepAlive

Reputation: 6665

What follows only makes sense if you do not have the control in the first place on how the dataframes are created (cf. the last section of the answer for a common-sense suggestion).


What about mapping objects to their identity using the globals() (or locals()) function? Thus, let's first define get_name_of, a custom function to do this job

def get_name_of(o):
    o_id = id(o)
    for objname, obj in globals().items():
        obj_id = id(obj)
        if obj_id == o_id:
            return objname

And then use it as follows

>>> get_name_of(dept[0])
'Phy'


That being shown, having to do such thing may be a signal that your code should be somehow "redesigned". If you have the control in the first place on how/when/where the dataframes are created, the best approach is to directly store them in a dictionary with their name. I.e. doing

your_dict = {}
# ...
your_dict['Chem'] = pd.DataFrame(...)

# and so on...

Upvotes: 3

Related Questions