0

I am really confused by below two cases on how the variable works in Python:

Case1: This case works as I expected: a keep as 1, doesn't matter it is in the function or out of the function

enter image description here

Case2: This case really makes me confused: why df1 is changed? I expect to save the change to df2, and df1 is kept as the original dataframe, which is important for the following process.

enter image description here

May I ask for your help on case 2: how to keep df1 as the original dataframe? Thanks.

Annie
  • 85
  • 3
  • 14
  • Make a copy of it? – dfundako Jan 26 '21 at 15:09
  • What do you mean? I screenshot from my notebook in order to show the result. Should I copy the codes here? – Annie Jan 26 '21 at 15:10
  • 1
    Does this answer your question? [List changes unexpectedly after assignment. How do I clone or copy it to prevent this?](https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-how-do-i-clone-or-copy-it-to-prevent) The question is about lists, but the principle of reference assignment is the same. – bbnumber2 Jan 26 '21 at 15:12
  • 4
    When you do `df2 = df1`, you're pointing the variable `df2` to the same object that `df1` is pointing at. If you then modify, say, `df1['new4']`, then you'll be able to see the change reflected in `df2`, because they're the same object. I think the other commenter means, have you tried doing `df2 = df1.copy()`, which would result in `df2` being "different but identical", rather than "the same" – Green Cloak Guy Jan 26 '21 at 15:12
  • 2
    Read https://nedbatchelder.com/text/names.html. – chepner Jan 26 '21 at 15:12
  • Remember to paste your code between sets of three backsticks (`). – CATboardBETA Jan 26 '21 at 15:15
  • Thank you all. You are all right. But this is just a trial case, in my real project, the df1 has more than 8k rows with 400 columns, if copy it, would it increase the volume greatly? – Annie Jan 26 '21 at 15:17
  • I think concepts about [the scopes in Python](https://www.w3schools.com/python/python_scope.asp) would help the first case. – Yang Yushi Jan 26 '21 at 15:18
  • @Annie yes, it would, *but how else could it possible work?*. If you want two independent objects, you have to use twice the memory (there's a reason why Python doesn't implicitly make copies when you assign) – juanpa.arrivillaga Jan 26 '21 at 16:17
  • As an aside, in the future, please don't post *images* of code. Post all code as formatted text. – juanpa.arrivillaga Jan 26 '21 at 16:27

0 Answers0