1

Here's the example I have

data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings',
         'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'],
         'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2],
         'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017],
         'Points':[876,789,863,673,741,812,756,788,694,701,804,690]}
data = pd.DataFrame(data)
data.head()

I get a warning from pandas library when I do this

from sklearn.model_selection import train_test_split
train_new, val_new = train_test_split(data, test_size=0.2)

col = 'Team'
means = data.groupby(col)['Points'].mean()
train_new[col + '_mean_target'] = train_new[col].map(means)
train_new.head()

This is the warning

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

And when I use the .loc

col = 'Team'
means = data.groupby(col)['Points'].mean()
train_new.loc[:,col + '_mean_target'] = train_new.loc[:,col].map(means)
train_new.head()

it shows the same exact warning, so what's wrong with the code?

rgap
  • 61
  • 2
  • 8
  • I'm confused, the data you posted doesn't line up. It's not even syntactically correct. What do you mean? – Rushabh Mehta Jul 15 '18 at 00:56
  • It is syntactically correct, but maybe I should post a smaller example. – rgap Jul 15 '18 at 01:11
  • I swear I ran into this issue before using almost your same exact code so I usually just ignore it. I'm currently looking for a solution though because I'm tired of seeing it. I'll report back if I find anything that works. – bbennett36 Jul 16 '18 at 21:14

1 Answers1

0

another way is to disable chained assignments, which works on your code without the need to create a copy:

# disable chained assignments
pd.options.mode.chained_assignment = None

This is an answer from this related problem (wouldn't say it's a duplicate question) - Pandas DataFrame: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame

bbennett36
  • 6,065
  • 10
  • 20
  • 37