Reputation: 149
I am a newbie to Python. Currently running 3.5.2.
I would like a function to be able to capture the name of a pandas DataFrame that it has been passed.
Rather than printing the DataFrame contents when I run my function, as my example below does, is there a way to get the DataFrame name (i.e. "df")?
Thanks for any suggestions
#### Test Code ####
# Import pandas module
import pandas as pd
# Create DataFrame
df = pd.DataFrame({"A":[1,2,3], "B":[10,20,30]})
# Define Function
def test(data):
print("Dataframe Name is: %s" % data)
print(data.describe())
# Run Function
test(df)
Upvotes: 7
Views: 26095
Reputation: 4417
Use globals()
and search for the object matching the local variable data
#### Test Code ####
# Import pandas module
import pandas as pd
# Create DataFrame
df = pd.DataFrame({"A":[1,2,3], "B":[10,20,30]})
# Define Function
def test(data):
name =[x for x in globals() if globals()[x] is data][0]
print("Dataframe Name is: %s" % name)
print(data.describe())
# Run Function
test(df)
The result will be:
Dataframe Name is: df
A B
count 3.0 3.0
mean 2.0 20.0
std 1.0 10.0
min 1.0 10.0
25% 1.5 15.0
50% 2.0 20.0
75% 2.5 25.0
max 3.0 30.0
Upvotes: 14
Reputation: 5488
Just name the dataframe as follows, and modify your function.
import pandas as pd
# Create DataFrame
df = pd.DataFrame({"A":[1,2,3], "B":[10,20,30]})
df.name = 'mydf'
# Define Function
def test(data):
print("Dataframe Name is: %s" % df.name)
print(data.describe())
Dataframe Name is: mydf
A B
count 3.0 3.0
mean 2.0 20.0
std 1.0 10.0
min 1.0 10.0
25% 1.5 15.0
50% 2.0 20.0
75% 2.5 25.0
max 3.0 30.0
# Run Function
test(df)
Upvotes: 2