Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

python - 'A value is trying to be set on a copy of a slice from a DataFrame' error while using 'iloc'

Jupiter nootbook is returning this warning:

*C:anacondalibsite-packagespandascoreindexing.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

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:anacondalibsite-packagespandascoreindexing.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

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

self.obj[item] = s*

After runing the following code:

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you need copy:

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...