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
dfandareference the exact same object. Making changes to that object will be visible from bothdfanda. You likely want to makeaa copy ofdf.a = dfdoes not make a copy of the value. Read nedbatchelder.com/text/names.html.