0

I have a list of dataframes in python.

sensors = [df_x, df_y, df_z]

df_x, df_y, df_z are dataframes

How to get name of the dataframe?

Ex: df_x, df_y, df_z

  • 1
    Isn't `df_x` just a variable? what exactly are you trying to do? – Guy Jul 25 '22 at 12:17
  • 5
    Python variables are not the names *of* objects, just names your code uses to *refer* to objects. The objects themselves don't know what variables refer to them, only how *many* references to them exist. – chepner Jul 25 '22 at 12:19
  • Rather then a list of dataframes you could have a dictionary of dataframes with the keys being the intended names of the dataframes. – John Coleman Jul 25 '22 at 12:35
  • those are not the "names" of the dataframes. Those are just variables that happen to refer to those dataframes. If you want to associate a string with a dataframe, you should create a data structure that makes that association directly, e.g. a `dict` or even a list of `tuple`s – juanpa.arrivillaga Jul 25 '22 at 18:28

3 Answers3

0
df_x = ['df_x', (variable)]
df_y = ['df_x', (variable)]    
df_z = ['df_x', (variable)]  
sensors = [df_x[1], df_y[1], df_z[1]]

if you want to know variable name in string, df_x[0] is that one.

ksc
  • 11
  • 1
0

If a variable starts with df_ is a dataframe to you. You can use this.

# If the values of the list are strings
sensors = ['df_x', 'df_y', 'df_z']

for i in sensors:
    if i.startswith("df_"):
        print(f"{i} is a dataframe")
    print(f'{i} is not a dataframe')
0

As was pointed out in the comments you can't know the name of the df, as in the name of the df-object in your code (atleast not without using some dodgy python magic).

But if you can modify the df's while you still know what you want to call them, there actually is a way without storing the name and df separately in a dict or tuple as was suggested. You can name the df directly by using a custom attribute:

import pandas as pd


df_x = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b'])
df_x.attrs['name'] = 'df_x'

print(df_x)
print(f"Name of df_x: {df_x.attrs.get('name', None)}")

Gives the output:

Name of df_x: df_x

You could do exactly the same by saving and retrieving the name through df.name (or using any other like df.h9d32 for that matter) but if there is a column name (resp. h9d32) in your dataframe it would overwrite it. Using .attrs is safer in this regard.

MangoNrFive
  • 1,541
  • 1
  • 10
  • 23