2

I perform a copy inside a function and return a new dictionary but it seems the original dictionary is also modified. Does anyone know why? and how to fix this:

Note: The input is dictionary of dataframe. This mean that each value is dictionary.

Here is an example:

def Testing(data,col1,col2):
  data2 = data.copy()
  for ii in data:
     data2[ii].drop([col1,col2],axis=1, inplace=True)

  return data2

Calling the above function like this:

Data_new = Testing(Data, col1,col2)

It seems both Data and Data_new have similar columns and are identical. Can anyone tell me why and how to fix it?

user59419
  • 893
  • 8
  • 20

1 Answers1

1

As someone mentioned in the comments, you are having a shallow copy vs deep copy problem. The copy method makes a shallow copy, while the deepcopy method makes a deep copy and completely separates the new and old dictionaries.

from copy import deepcopy
def Testing(data,col1,col2):
  data2 = deepcopy(data)
  for ii in data:
     data2[ii].drop([col1,col2],axis=1, inplace=True)
  return data2


Data_new = Testing(Data, col1,col2)
PurpleHacker
  • 358
  • 2
  • 9