what is the difference between target = train['claim'] and target = train['claim'].copy()?

Viewed 51

Considering train is a Pandas dataframe, what is the difference between these two?

  • target = train['claim']‍
  • target = ‍train['claim'].copy()‍

Since both these code snippets are used to assign the value of the column to a target variable, how are they different?

2 Answers

target = train['claim'] means that target will point to the exact same object stored in train['claim']. Any modification done to this object via either target or train['claim'] will affect both.

target = train['claim'].copy() means you're creating a copy of whatever's in train['claim'] and storing it to target. Subsequent modifications to the object in traint['claim'] won't affect target, and vice-versa.

It is hard to tell without seeing the context but I am assuming train["claim"] is a list. The .copy() method creates a copy of a list which means that when you change the variable named "target" you won't also be changing the value of train["claim"]. The reason it would normally change the value is because lists are mutable, which means they can be changed after they were created. Most variables, such as ints, strings and tuples are immutable. When you change them you are in reality creating a new variable with the same name as the old one but since this is not the case with lists, both variables get edited when you change the list. The .copy() method stops this from happening. For example, run the following code:

a = ["a", "b"]
print(id(a))
b = a
print(id(b))
c = ["c", "d"]
print(id(c))
d = c.copy()
print(id(d))

In the first case, a and b are stored in the same place in memory (have the same id) so changing one affects the other. But in the second case, there are two different lists stored in different places in memory

Related