python - 尝试使用函数中定义的数据框名称时发生意外的名称错误

标签 python python-2.7 pandas

有人可以解释一下为什么下面的代码会产生NameError吗?

def nonull(df, col, name):
    name = df[pd.notnull(df[col])]
    print name[col].count(), df[col].count()
    return name

nonull(sve, 'DOC_mg/L', 'sveDOC')
sveDOC.count()

NameError: name 'sveDOC' is not defined

711 711

dataframe 似乎是在 print 语句工作时创建的,所以我不明白为什么当我尝试使用 sveDOC (这是函数内的 name),它会产生错误。

这是我想在该函数中执行的操作的示例:

import pandas as pd

d = {'one' : pd.Series([1., 1., 1., 1.], index=['a', 'b', 'c', 'd']), 
     'two' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
pd.DataFrame(d)
df = pd.DataFrame(d)
df1 = df
df = df * 2
print df.head(), df1.head()

one  two
a    2    2
b    2    4
c    2    6
d    2    8    
one  two
a    1    1
b    1    2
c    1    3
d    1    4

最佳答案

Python 名称​​并不按照您想象的方式工作。这是您的代码实际执行的操作:

def nonull(df, col, name):
    name = df # rebind the name 'name' to the object referenced by 'df'
    name = df[pd.notnull(name[col])] # rebind the name 'name' again 
    print name[col].count(), df[col].count()
    return name # return the instance

nonull(sve, 'DOC_mg/L', 'sveDOC') # call the function and ignore the return value

该函数实际上从未使用'sveDOC' 参数。这是你实际应该做的:

def nonull(df, col):
    name = df[pd.notnull(df[col])]
    print name[col].count(), df[col].count()
    return name

sveDOC = nonull(sve, 'DOC_mg/L')
sveDOC.count()
<小时/>

您对 Python 使用名称和引用的看法是完全错误的。

pd.DataFrame(d) # creates a new DataFrame but doesn't do anything with it
                # (what was the point of this line?)
df = pd.DataFrame(d) # assigns a second new DataFrame to the name 'df'
df1 = df # assigns the name `df1` to the same object that 'df' refers to
         # - note that this does *not* create a copy
df = df * 2 # create a new DataFrame based on the one referenced by 'df' 
            # (and 'df1'!)and assign to the name 'df'

为了证明这一点:

df1 = pd.DataFrame(d)

df2 = df1

df1 is df2
Out[5]: True # still the same object

df2 = df2 * 2

df1 is df2
Out[7]: False # now different

如果您想创建 DataFrame 的副本,请明确执行此操作:

df2 = copy(df1)

您可以在 nonull 外部执行此操作并传递副本,也可以在 nonull 内部执行此操作并返回修改后的副本。

关于python - 尝试使用函数中定义的数据框名称时发生意外的名称错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24231437/

相关文章:

python - 通过 Python 连接到托管在远程服务器上的 MySQL 数据库,但无法直接访问

python - 使用列条件处理数据框的子集

java - 使用 Python 创建和实现接口(interface)?

linux - 仅复制目录中的文件而不是目录中的文件

python - 子解析器 argparse "error: too few arguments"

python - float 日期转换

python - 使用 boto3 获取新创建的亚马逊 ec2 实例的公共(public) IPv4 地址

python - Homebrew 没有正确链接 python?

python - 匹配 DataFrame 中的相似值

python - Pandas groupby 获得平均一天