Skip to content
Advertisement

Misunderstanding of global variable in Python

I would like to calculate the variable “a” by using a function and the global variable “df”. My problem is that after running the function, “df” is also altered. I just want to calculate “a” with the function, but I want that “df” stays as it is.

import pandas as pd
f=[]
df = pd.DataFrame(f)
df['A']=[1]

print(df)

def fun():
    a=df
    a['A']=a['A']+1
    return a

fun()
print(df)

actual result:

   A
0  1

   A
0  2

expected result:

   A
0  1

   A
0  1

Advertisement

Answer

when you are assiging a = df. they are referencing to same thing. So when you’re changing some property in a, the df also gets changed. As you do not want to change df inside function, just use copy() and work with the copy. Inside fun(), do:

a = df.copy()
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement