0

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
2
  • 2
    Note that both df and a reference the exact same object. Making changes to that object will be visible from both df and a. You likely want to make a a copy of df. Commented Jul 21, 2021 at 12:42
  • 2
    a = df does not make a copy of the value. Read nedbatchelder.com/text/names.html. Commented Jul 21, 2021 at 12:43

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.