【问题标题】:'A value is trying to be set on a copy of a slice from a DataFrame' error while using 'iloc'使用“iloc”时,“试图在来自 DataFrame 的切片的副本上设置值”错误
【发布时间】:2018-03-25 11:37:00
【问题描述】:

Jupiter nootbook 正在返回此警告:

*C:\anaconda\lib\site-packages\pandas\core\indexing.py:337: 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

请参阅文档中的注意事项:http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

self.obj[key] = _infer_fill_value(value)
C:\anaconda\lib\site-packages\pandas\core\indexing.py:517: 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

请参阅文档中的注意事项:http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

self.obj[item] = s*

运行以下代码后:

def group_df(df,num):
    ln = len(df)
    rang = np.arange(ln)
    splt = np.array_split(rang,num)
    lst = []
    finel_lst = []
    for i,x in enumerate(splt):
        lst.append([i for x in range(len(x))])
    for k in lst:
        for j in k:
            finel_lst.append(j)
    df['group'] = finel_lst
    return df
def KNN(dafra,folds,K,fi,target):        
    df = group_df(dafra,folds)
    avarge_e = []
    for i in range(folds):
        train = df.loc[df['group'] != i]
        test = df.loc[df['group'] == i]
        test.loc[:,'pred_price'] = np.nan
        test.loc[:,'rmse'] = np.nan
        print(test.columns)
KNN(data,5,5,'GrLivArea','SalePrice')    

在错误消息中,建议使用.loc indexing- 我这样做了,但没有帮助。请帮帮我-有什么问题?我已经完成了相关问题并阅读了文档,但我仍然不明白。

【问题讨论】:

  • 它是否说明警告出现在哪一行以及您之前的版本是什么?
  • 编辑以包含整个警告
  • 既然问题已经回答了,只是一件小事。你可以用这个df['groups'] = pd.qcut(range(len(df)), folds, labels=False, retbins=True)[0] 替换你的group_df 方法,这是pandas 的一个内置函数,它应该创建相同大小的垃圾箱。 pandas.pydata.org/pandas-docs/stable/generated/pandas.qcut.html

标签: python pandas


【解决方案1】:

我觉得你需要copy:

train = df.loc[df['group'] != i].copy()
test = df.loc[df['group'] == i].copy()

如果您稍后修改 test 中的值,您会发现修改不会传播回原始数据 (df),并且 Pandas 会发出警告。

【讨论】:

  • 谢谢!有效。请向我解释问题出在哪里以及您的建议是如何解决的? :)
  • 是的,请稍等。
  • 所以,loc 索引会在原始 df 中创建一个“视图”,这意味着对它们的任何更改也将应用于原始 df ?而且我不希望这种情况发生我需要使用'.copy()'?
猜你喜欢
  • 2021-08-09
  • 2016-12-22
  • 1970-01-01
  • 2017-06-19
  • 2016-09-23
  • 2016-02-17
  • 2016-08-24
  • 2016-06-16
相关资源
最近更新 更多