-1

Using the Python package PANDAS, I have a simple loop where I want to print some data frame information

for df in (df1, df2, df3, df4, df5, df6, df7):
    print(df.keys())

However, I also want to label each dataframe with its variable name (ex: df1 or df2). Is there a way to print the variable name?

Looking at How do I print the variable name holding an object? there doesn't seem to be a good answer for java but I'm not sure with Python. Any tips? Thanks.

Bojan Milinic
  • 93
  • 1
  • 1
  • 7
  • Are they always named by "df" and the numbers from 1 to n? In this case you could use enumerate to iterate and print df with the proper index. – Tobotis Oct 27 '22 at 18:36
  • 1
    Store the dataframes in a dictionary rather than a tuple: `dict_frames = {f'df{i}':df for i,df in enumerate([df0, df1, df2, . . . ])}` – It_is_Chris Oct 27 '22 at 18:37
  • If I'm understanding your question, adding a = in an f-string like so print(f"{df =}") – Jason Baker Oct 27 '22 at 18:41
  • 1
    This is not possible, objects are not aware of the names that point to them. Also they can have more than one, or none. – mozway Oct 27 '22 at 18:41
  • @Tobotis I just named it that way for this example but every df have a different name based on letters – Bojan Milinic Oct 27 '22 at 18:51
  • What are you trying to achieve? What does your expected output look like? – Azhar Khan Oct 28 '22 at 04:40

1 Answers1

2

Use zip() to iterate over two lists simultaneously.

dfs=[df1, df2, df3, df4, df5, df6, df7]
dfs_names=['df1', 'df2', 'df3', 'df4', 'df5', 'df6', 'df7']

for name, df in zip(dfs_names, dfs):
  print(n ,df.keys())