0

I have a simple process, trying to add the array prob_win as a new column of an existing data frame df. They have the same dimension as shown below:

print type(prob_win)
print len(prob_win)
print df.shape

<type 'numpy.ndarray'>
799
(799, 1)

I then did the following assignment:

df['prob_win'] = prob_win

The code works but have the following warning:

 1 Warning
/opt/conda/envs/python2/lib/python2.7/site-packages/ipykernel/__main__.py:14: 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

So I changed to use .loc as the warning said:

df.loc[:,'prob_win'] = prob_win

But still got the same error. What did I do wrong here? How do I get rid the warning in this case? Thanks!

jpp
  • 159,742
  • 34
  • 281
  • 339
Edamame
  • 23,718
  • 73
  • 186
  • 320
  • 1
    bro this question comes over and over and over again. nothing to worry about, just read the documentation to make sure you understand what's going on. Getting tons of these warnings and I am still alive – ℕʘʘḆḽḘ Apr 02 '18 at 18:34
  • what is code above `df['prob_win'] = prob_win` ? some filtering? – jezrael Apr 02 '18 at 18:37
  • 4
    I would guess that the dataframe "df" is already a slice of another dataframe. i.e. you set `df = df_original[someMaskCriteria]` – Dan Fiorino Apr 02 '18 at 18:43
  • 2
    Possible duplicate of [How to deal with SettingWithCopyWarning in Pandas?](https://stackoverflow.com/questions/20625582/how-to-deal-with-settingwithcopywarning-in-pandas) – johnchase Apr 02 '18 at 18:56

1 Answers1

2

If the warning is matter .

df=df.assign(prob_win=prob_win)
BENY
  • 317,841
  • 20
  • 164
  • 234
  • `assign` is also much faster than `[] =` assignment (even with `loc`). Sometimes I got ridiculously slow time of `[]` assignment, like 1 second for 1000 rows. No problems like that with `assign`. – Dennis Golomazov Apr 02 '18 at 19:18
  • @DennisGolomazov yep , sometime it happens . :-) – BENY Apr 02 '18 at 19:20