Skip to main content
 首页 » 编程设计

python之打印数据框名称

2025年05月04日16fff_TT

我是 Python 新手。当前运行 3.5.2。

我想要一个函数能够捕获它已传递的 pandas DataFrame 的名称。

有没有办法获取 DataFrame 名称(即“df”),而不是像我下面的示例那样在运行我的函数时打印 DataFrame 内容?

谢谢你的建议

#### 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) 

请您参考如下方法:

使用globals() 并搜索与局部变量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) 

结果将是:

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