将数据帧传递给函数时,大 pandas 何时通过引用传递Vs通过值传递? [英] When does pandas do pass-by-reference Vs pass-by-value when passing dataframe to a function?

查看:111
本文介绍了将数据帧传递给函数时,大 pandas 何时通过引用传递Vs通过值传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def dropdf_copy(df):
    df = df.drop('y',axis=1)

def dropdf_inplace(df):
    df.drop('y',axis=1,inplace=True)    

def changecell(df):
    df['y'][0] = 99


x = pd.DataFrame({'x': [1,2],'y': [20,31]})

x
Out[204]: 
   x   y
0  1  20
1  2  31

dropdf_copy(x)

x
Out[206]: 
   x   y
0  1  20
1  2  31

changecell(x)

x
Out[208]: 
   x   y
0  1  99
1  2  31

在上面的示例中,dropdf()不会修改原始数据帧x,而changecell()会修改x.我知道如果我将较小的更改添加到changecell(),它将不会更改x.

In the above example dropdf() doesnt modify the original dataframe x while changecell() modifies x. I know if I add the minor change to changecell() it wont change x.

def changecell(df):
    df = df.copy()
    df['y'][0] = 99

我认为在我编写的每个函数中都包含df = df.copy()并不十分优雅.

I dont think its very elegant to inlcude df = df.copy() in every function I write.

问题

Questions

1)大熊猫在什么情况下会更改原始数据框,何时不更改?有人可以给我一个明确的可概括性规则吗?我知道这可能与可变性与不可变性有关,但在stackoverflow中没有明确解释.

1) Under what circumstances does pandas change the original dataframe and when it does not? Can someone give me a clear generalizable rule? I know it may have something to do with mutability Vs immutability but its not clearly explained in stackoverflow.

2)numpy是否具有类似的行为或与之不同?那其他的python对象呢?

2) Does numpy behave simillary or its different? What about other python objects?

PS:我已经对stackoverflow进行了研究,但是找不到针对此问题的明确的通用规则.

PS: I have done research in stackoverflow but couldnt find a clear generalizable rule for this problem.

推荐答案

默认情况下,python确实通过引用传递.仅当在类似赋值的函数中进行了显式复制或使用了copy()函数时,传递的原始对象才保持不变.

By default python does pass by reference. Only if a explicit copy is made in the function like assignment or a copy() function is used the original object passed is unchanged.

带有显式副本的示例:

#1. Assignment 
def dropdf_copy1(df):

    df = df.drop('y',axis=1)
#2. copy()
def dropdf_copy2(df):
    df = df.copy() 
    df.drop('y',axis=1,inplace = True)

如果未执行显式复制,则更改传递的原始对象.

If explicit copy is not done then original object passed is changed.

def dropdf_inplace(df):
    df.drop('y',axis=1,inplace = True)

这篇关于将数据帧传递给函数时,大 pandas 何时通过引用传递Vs通过值传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆