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

2024-05-16 01:38:07 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能解释一下为什么下面的代码会产生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)时,它会产生错误。在

下面是我希望在函数中执行的操作的示例:

^{pr2}$

Tags: 函数代码namedfreturndefcountcol
1条回答
网友
1楼 · 发布于 2024-05-16 01:38:07

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'参数。以下是您实际应该做的:

^{pr2}$

你对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和{}内部执行。在

相关问题 更多 >