使用iloc时,“试图在DataFrame的切片副本上设置一个值"错误 [英] 'A value is trying to be set on a copy of a slice from a DataFrame' error while using 'iloc'

查看:77
本文介绍了使用iloc时,“试图在DataFrame的切片副本上设置一个值"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Jupiter Nootbook返回此警告:

Jupiter nootbook is returning this warning:

*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

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

See the caveats in the documentation: 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索引编制,但没有帮助.请帮助我-什么问题?我已经解决了相关问题并阅读了文档,但是我仍然不明白.

In the error message, it is recommended to use .loc indexing- which i did, but it did not help. Please help me- what is the problem ? I have went through the related questions and read the documentation, but i still don't get it.

推荐答案

我认为您需要

I think you need copy:

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

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

If you modify values in test later you will find that the modifications do not propagate back to the original data (df), and that Pandas does warning.

这篇关于使用iloc时,“试图在DataFrame的切片副本上设置一个值"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆