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


Read more here: https://stackoverflow.com/questions/68469622/misunderstanding-of-global-variable-in-python

Content Attribution

This content was originally published by ZetDen at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: