Passing pandas DataFrame by reference
<p>My question is regarding immutability of pandas DataFrame when it is passed by reference. Consider the following code:</p>

<pre><code>import pandas as pd

def foo(df1, df2):

    df1['B'] = 1
    df1 = df1.join(df2['C'], how='inner')

    return()

def main(argv = None):

    # Create DataFrames. 
    df1 = pd.DataFrame(range(0,10,2), columns=['A'])
    df2 = pd.DataFrame(range(1,11,2), columns=['C'])

    foo(df1, df2)    # Pass df1 and df2 by reference.

    print df1

    return(0)

if __name__ == '__main__':
    status = main()
    sys.exit(status)
</code></pre>

<p>The output is</p>

<pre><code>   A  B  
0  0  1
1  2  1
2  4  1
3  6  1
4  8  1
</code></pre>

<p>and not </p>

<pre><code>   A  B  C
0  0  1  1
1  2  1  3
2  4  1  5
3  6  1  7
4  8  1  9
</code></pre>

<p>In fact, if foo is defined as</p>

<pre><code>def foo(df1, df2):

    df1 = df1.join(df2['C'], how='inner')
    df1['B'] = 1

    return()
</code></pre>

<p>(i.e. the "join" statement before the other statement) then the output is simply</p>

<pre><code>   A    
0  0 
1  2 
2  4 
3  6 
4  8
</code></pre>

<p>I'm intrigued as to why this is the case. Any insights would be appreciated.</p>

<p>Python doesn't have pass by value vs. pass by reference - there are just <a href="https://docs.python.org/2/reference/executionmodel.html#naming-and-binding" rel="nofollow">bindings from names to objects</a>. </p>

<p>If you change your function to</p>

<pre><code>def foo(df1, df2):

    res = df1.join(df2['C'], how='inner')
    res['B'] = 1

    return res
</code></pre>

<p>Then <code>df1</code>, <code>df2</code>, in the function, are bound to the objects you sent. The result of the <code>join</code>, which is a new object in this case, is bound to the name <code>res</code>. You can manipulate it, and return it, without affecting any of the other objects or bindings. </p>

<p>In your calling code, you could just write</p>

<pre><code>print foo(df1, df2)
</code></pre>

python pandas dataframe pass-by-reference immutability