[英]Python function transfering the pandas Dataframe attributes doesn't work
It'a simple example. 这是一个简单的例子。
d=pd.DataFrame({'a':[1,2,3,4],
'b':[6,6,7,8]})
I write a function f(x).I want to print dx The function is: 我写了一个函数f(x)。我想打印dx该函数是:
def f(x):
print(d.x)
Run f(a)
. 运行f(a)
。 I expect it to print da
我希望它打印da
But it returns NameError: name 'a' is not defined
. 但是它返回NameError: name 'a' is not defined
。 How do I solve it? 我该如何解决?
You can't approach it that way, you would need a function that get's column by [
]
, and enter a string as well: 您无法以这种方式进行处理,您需要一个通过[
]
获取列的函数,并且还要输入一个字符串:
def f(x):
print(d[x])
And to call it: 并称之为:
f('a')
you have to write xa
if you try to pass dataframe in function which is locally x 如果您尝试在本地x的函数中传递数据帧,则必须编写xa
def f(x):
print(x.a)
but if you pass column name then and dataframe is global variable then you could use below 但是,如果您传递列名,并且dataframe是全局变量,则可以在下面使用
def f(x):
print(d[x])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.