When does pandas do pass-by-reference Vs pass-by-value when passing dataframe to a function?

谁都会走 提交于 2019-12-04 17:18:12

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.

Example with explicit copy :

#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)

Nothing to deal with pandas. It'a problem of local/global variables on mutable values. in dropdf, you set df as a local variable.

The same with lists:

def global_(l):
    l[0]=1

def local_(l):
    l=l+[0]  

in the second function, it will be the same if you wrote :

def local_(l):
    l2=l+[0]

so you don't affect l.

Here the python tutor exemple which shoes what happen.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!