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
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
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.
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')
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.