0

I have a pandas dataframe with three columns: Close, Open and Target. The "Target" column is supposed to equal (Close - Open)/Open. But the following line generates a "SettingWithCopyWarning", which is hard to understand, because this expression would not generate a problem with numpy arrays. The line that generates the warning is this:

df["Target"] = (df["Close"] - df["Open"])/df["Open"]

And the warning message is hard to understand. Here is the warning message:

A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

How to modify the original code to make the warning go away?

Alex
  • 305
  • 4
  • 10
  • Does it answer your question? https://stackoverflow.com/questions/20625582/how-to-deal-with-settingwithcopywarning-in-pandas – Arkadiusz Nov 03 '21 at 14:26
  • no, i dont understand how to modify my code, even after reading that. I read it before I posted this question. – Alex Nov 03 '21 at 14:27
  • @Alex your `df` is a slice of a bigger dataframe. You need to update that bigger data frame with `big_df.loc[df.index, 'Target'] = (df['Close'] - df['Open'])/df['Open'])`. – Quang Hoang Nov 03 '21 at 14:31
  • df was created by df = another_df.dropna(). Had no idea that this line would create a slice. I thought that df was a new independent dataframe. Thanks a lot for that clarification. – Alex Nov 03 '21 at 14:38
  • You can do: df = another_df.dropna().reset_index(drop=True) in the previous operation and then go with the line you pasted in your post. – Arkadiusz Nov 03 '21 at 14:40

0 Answers0