Videgain
Videgain

Reputation: 195

Why replacing a value in a DataFrame also replaces it in the original DataFrame

I have a DataFrame 'Datos' with a long amount of dates in the index. I want to take a particular period of time so I define another dataframe as AntCris=Datos.loc['2005-01-01':'2007-07-01'] and then I do some operations over 'AntCris' while replacing the result inside 'AntCris'. The code I use for those replacement do not work properly but this is not the point. Here is the code:

for x in AntCris.columns:
  aux=AntCris[x].dropna()
  aux2=aux.iloc[0]
  print(x)
  for y in AntCris[x].values:
    if np.isnan(y)==True:
      b=2
    else:
      a=np.log(y)-np.log(aux2)
      AntCris[x]=AntCris[x].replace([y],a)

Once the error stops this code running, sometimes I get AntCris modified but also Datos. How could I avoid that? I just want to do the changes on AntCris or even in a copy of 'Datos' but keeping the original as it was.

Upvotes: 0

Views: 63

Answers (2)

Utsav
Utsav

Reputation: 5918

Slicing creates shallow copy whereas copy method can be used to create a deep copy. Deep copy results in independent copy of the original dataframe.

To get deep copy of Datos, please use below command.

AntCris = Datos.copy()

Upvotes: 1

Abhilash Rajan
Abhilash Rajan

Reputation: 349

To create a true copy of your dataframe, you can use the below command:

AntCris = Datos.copy()

Upvotes: 1

Related Questions