Home > Net >  Get pandas dataframe names stored in list in 2 loops instead of iterator name
Get pandas dataframe names stored in list in 2 loops instead of iterator name

Time:06-20

I am attempting to get the dataframe names stored in the lists, iterating through 2 loops. Instead of getting the dataframe name itself like cat or sunday, I am getting the iterator name like df.

def get_df_name(df):
    name =[x for x in globals() if globals()[x] is df][0]
    return name

cat = pd.DataFrame()  
dog = pd.DataFrame()  
sunday = pd.DataFrame()  
monday = pd.DataFrame()  

for df in [cat, dog]:
    for df1 in [sunday, monday]:
            print('---------')
            print(get_df_name(df)   ' and '   get_df_name(df1))

Currently my output is below


---------
df and df1
---------
df and df1
---------
df and df1
---------
df and df1

But I am expecting

---------
cat and sunday
---------
cat and monday
---------
dog and sunday
---------
dog and Monday

CodePudding user response:

import pandas as pd
import inspect

def retrieve_name(var):
   callers_local_vars = inspect.currentframe().f_back.f_globals.items()
   return [var_name for var_name, var_val in callers_local_vars if var_val is var][0]

cat = pd.DataFrame()  
dog = pd.DataFrame()  
sunday = pd.DataFrame()  
monday = pd.DataFrame()
list1,list2 = [cat, dog],  [sunday, monday]
for x in range(len(list1)):
    for y in range(len(list2)):
        print('---------')
        print(retrieve_name(list1[x])   ' and '  retrieve_name(list2[y]) )

enter image description here

  • Related