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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With