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.
JavaScript
x
15
15
1
import pandas as pd
2
f=[]
3
df = pd.DataFrame(f)
4
df['A']=[1]
5
6
print(df)
7
8
def fun():
9
a=df
10
a['A']=a['A']+1
11
return a
12
13
fun()
14
print(df)
15
actual result:
JavaScript
1
6
1
A
2
0 1
3
4
A
5
0 2
6
expected result:
JavaScript
1
6
1
A
2
0 1
3
4
A
5
0 1
6
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:
JavaScript
1
2
1
a = df.copy()
2