Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print DataFrame Name

Tags:

python

pandas

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)
like image 352
Pete B Avatar asked Jul 16 '26 11:07

Pete B


1 Answers

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
like image 120
sgDysregulation Avatar answered Jul 19 '26 01:07

sgDysregulation



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!