0

I'm just not getting this and I have read the documentation or I wouldn't be here. I have tried many many variations of the following code, but I always get the warning. The code does produce the result I want, but I just want to know how to get it right. ChatGPT couldn't get it either. I've read the chain indexing, etc. But after way too much time, I wanted to know if anyone see what's going wrong here. Thank you so much in advance.

This code :

sp500.loc[:, new_col_name] = sp500.loc[:, col]/sp500.loc[:, 'close']

Says: Try using .loc[row_indexer,col_indexer] = value instead

It started as:

sp500[new_col_name] = sp500[col]/sp500['close']

Which also produced the correct result, but had the same warning. I just want a new column based off 2 existing columns.

In the referenced duplicate is says this: Using df.loc[:, foo] avoids SettingWithCopyWarning, whereas df[foo] causes SettingWithCopyWarning.

Which is obviously what I'm not doing, or again I would not have posted the question.

roguecode
  • 45
  • 6
  • 1
    The question here is how `sp500` is created and what does the code that creates it look like – cs95 Apr 28 '23 at 15:09
  • Please use the [search options available here](https://stackoverflow.com/search?q=%5Bpandas%5D+settingwithcopywarning). (It's likely your question can be closed a duplicate of the top hit of those search results.) – 9769953 Apr 28 '23 at 15:11
  • sp500 = spy_data.copy() – roguecode Apr 28 '23 at 21:16
  • Not sure if this is the problem, but `sp500.loc[:, new_col_name] = sp500.loc[:, col]/sp500.loc[:, 'close']` can be written more simply as `sp500[new_col_name] = sp500[col] / sp500['close']` – Nick ODell Apr 28 '23 at 21:21

0 Answers0