熊猫尝试改用.loc [row_indexer,col_indexer] = value

时间:2018-07-15 00:10:06

标签: python pandas warnings

这是我的例子

这样做时,我从熊猫图书馆收到警告

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()

这是警告

SettingWithCopyWarning: 试图在DataFrame的切片副本上设置一个值。 尝试改用.loc [row_indexer,col_indexer] =值

当我使用.loc

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()

它显示了完全相同的警告,所以代码出了什么问题?

1 个答案:

答案 0 :(得分:0)

另一种方法是禁用链式分配,这适用于您的代码,而无需创建副本:

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

这是此相关问题的答案(不会说这是重复的问题)-Pandas DataFrame: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame