使用iloc时,“试图从DataFrame的切片副本上设置一个值”错误

发布于 2021-01-29 19:08:34

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索引编制(我这样做了,但没有帮助)。请帮助我-什么问题?我已经解决了相关问题并阅读了文档,但是我仍然不明白。

关注者
0
被浏览
49
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    我认为您需要copy

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

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



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看