有人可以解释为什么以下代码会生成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
答案 0 :(得分:2)
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
和return
修改后的副本中执行此操作。