0

I have a pandas dataframe (pandas version '0.24.2') and a list which have the same length.

I want to add this list as a column to the dataframe.

I do this:

df.loc[:, 'new_column'] = pd.Series(my_List, index=df.index)

but I receive this warning:

.../anaconda/lib/python3.7/site-packages/pandas/core/indexing.py:362: SettingWithCopyWarning: 
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

See the caveats in the documentation: http://pandas.pydata.org/pandas-
docs/stable/indexing.html#indexing-view-versus-copy
  self.obj[key] = _infer_fill_value(value)
.../anaconda/lib/python3.7/site-packages/pandas/core/indexing.py:543: SettingWithCopyWarning: 
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

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self.obj[item] = s

Am I doing something wrong?

Outcast
  • 4,967
  • 5
  • 44
  • 99
  • Try `df_new = df.copy()`, then `df_new['new_column'] = my_List`. Also, the current version is 1.0.3, you should upgrade. – Trenton McKinney May 06 '20 at 18:06
  • @TrentonMcKinney yes now I have no warning with what you suggested :) - what was the problem? – Outcast May 06 '20 at 18:09
  • Somewhere in your code you created a dataframe by pointing to another dataframe. These are just pointers, so when you change the copy (unless you use .copy()) you change the original. From `.copy()`: When ``deep=True`` (default), a new object will be created with a copy of the calling object's data and indices. Modifications to the data or indices of the copy will not be reflected in the original object (see notes below). – Trenton McKinney May 06 '20 at 18:11
  • One of the answers here [How to deal with SettingWithCopyWarning in Pandas?](https://stackoverflow.com/questions/20625582/how-to-deal-with-settingwithcopywarning-in-pandas) covers this topic. So we should close this question. – Trenton McKinney May 06 '20 at 18:13
  • @TrentonMcKinney, up to you on whether to close it or not - I do this before in my code: `df = df_old[df_old['ids'].isin(ids_selection)]`. Should I have done this differently to avoid the warning in the first place (without doing the `.copy()` later as you suggested)? – Outcast May 06 '20 at 18:18
  • `df = df_old[df_old['ids'].isin(ids_selection)].copy()` – Trenton McKinney May 06 '20 at 18:26
  • @TrentonMcKinney, ah ok because I thought that this `df = df_old[df_old['ids'].isin(ids_selection)].` by itself takes a deep copy (?). – Outcast May 06 '20 at 19:34

0 Answers0