简体   繁体   English

Python中的参考语义混乱

[英]Reference semantics confusion in Python

I'm trying to drop missing values from two Pandas dataframes: 我正在尝试从两个Pandas数据框中删除丢失的值:

Data1 = pd.read_csv(r"C:\Users\Zihao\Desktop\New\OBSTET.csv")

Data2 = pd.read_csv(r"C:\Users\Zihao\Desktop\New\PRODUCTOS.csv", index_col = 0)

def DropNan(Data1, Data2):
    Data1 = Data1.dropna()
    Data2 = Data2.dropna()

When I cal the method, it is not working (it doesn't drop the missing values). 当我校准该方法时,它不起作用(它不会删除丢失的值)。 I wonder what caused this problem? 我想知道是什么引起了这个问题?

My guess is that it related to reference semantics in Python I do not understand. 我的猜测是它与我不了解的Python中的引用语义有关。 Could someone explain? 有人可以解释吗?

In your function, Data1 and Data2 are parameters, and therefore local variables. 在您的函数中, Data1Data2是参数,因此是局部变量。 The fact that they happen to have the same name as your global variables is irrelevant (except in causing some extra confusion). 它们恰好与全局变量具有相同的名称这一事实是无关紧要的(除非引起一些额外的混乱)。

If you want to change the global variables, do it like this: 如果要更改全局变量,请执行以下操作:

def DropNan():
    global Data1, Data2
    Data1 = Data1.dropna()
    Data2 = Data2.dropna()

DropNan()

Or, if you want to take these two values as parameters, you almost certainly want to return two values: 或者,如果要将这两个值用作参数,则几乎可以肯定要返回两个值:

def DropNan(d1, d2):
    return d1.dropna(), d2.dropna()

Data1, Data2 = DropNan(Data1, Data2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM