pandas 打印数据帧名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41684553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Print DataFrame Name
提问by Pete B
I am a newbie to Python. Currently running 3.5.2.
我是 Python 的新手。当前运行 3.5.2。
I would like a function to be able to capture the name of a pandas DataFrame that it has been passed.
我想要一个函数来捕获它已传递的 Pandas DataFrame 的名称。
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")?
有没有办法在运行我的函数时打印 DataFrame 内容,如下例所示,有没有办法获取 DataFrame 名称(即“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)
回答by sgDysregulation
Use globals()
and search for the object matching the local variable data
使用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)
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
回答by ade1e
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)