为预测集群创建一个新列:SettingWithCopyWarning

Creating a new column for predicted cluster: SettingWithCopyWarning

不幸的是,这个问题将是重复的,但我无法在我的代码中解决这个问题,即使在查看了其他类似问题及其相关答案之后也是如此。 我需要将我的数据集拆分为训练测试数据集。但是,当我添加一个新列来预测集群时,我似乎犯了一些错误。 我得到的错误是:

/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:3: 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: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  This is separate from the ipykernel package so we can avoid doing imports until

关于这个错误有几个问题,但可能是我做错了什么,因为我还没有解决这个问题,我仍然得到与上面相同的错误。 数据集如下:

    Date    Link    Value   
0   03/15/2020  https://www.bbc.com 1
1   03/15/2020  https://www.netflix.com 4   
2   03/15/2020  https://www.google.com 10
...

我已将数据集拆分为训练集和测试集,如下所示:

import sklearn
from sklearn.model_selection import cross_validate
from sklearn.model_selection import train_test_split
import re
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
import nltk
import string as st 

train_data=df.Link.tolist()
df_train=pd.DataFrame(train_data, columns = ['Review'])
X = df_train

X_train, X_test = train_test_split(
        X, test_size=0.4).copy()
X_test, X_val = train_test_split(
        X_test, test_size=0.5).copy()
print(X_train.isna().sum())
print(X_test.isna().sum())

stop_words = stopwords.words('english')

def preprocessor(t):
    t = re.sub(r"[^a-zA-Z]", " ", t())
    words = word_tokenize(t)
    w_lemm = [WordNetLemmatizer().lemmatize(w) for w in words if w not in stop_words]
    return w_lemm


vect =TfidfVectorizer(tokenizer= preprocessor)
vectorized_text=vect.fit_transform(X_train['Review'])
kmeans =KMeans(n_clusters=3).fit(vectorized_text)

导致错误的代码行是:

cl=kmeans.predict(vectorized_text)
X_train['Cluster']=pd.Series(cl, index=X_train.index)

我觉得这两个问题应该对我代码有帮助:

How to deal with SettingWithCopyWarning in Pandas?

但是我的代码中仍然存在错误。

在将此问题作为重复问题关闭之前,您能否看一下并帮助我解决此问题?

恕我直言,train_test_split 给你一个元组,当你做 copy() 时,copy() 是一个 tuple's operation, not pandas'。这会触发 pandas' 臭名昭著的复制警告。

所以你只创建了元组的浅表副本,而不是元素。也就是说

X_train, X_test = train_test_split(X, test_size=0.4).copy()

相当于:

train_test = train_test_split(X, test_size=0.4)
train_test_copy = train_test.copy()
X_train, X_test = train_test_copy[0], train_test_copy[1]

由于 pandas 数据帧是指针,X_trainX_test 可能指向也可能不指向与 X 相同的数据。如果你想复制数据帧,你应该在每个数据帧上明确强制 copy()

X_train, X_test = train_test_split(X, test_size=0.4)
X_train, X_test = X_train.copy(), X_test.copy()

X_train, X_test = [d.copy() for d in train_test_split(X, test_size=0.4)]

然后每个X_trainX_test都是一个指向新内存数据的新数据帧。


更新:测试这段代码没有任何警告:

X = pd.DataFrame(np.random.rand(100,3))
X_train, X_test = train_test_split(X, test_size=0.4)
X_train, X_test = X_train.copy(), X_test.copy()

X_train['abcd'] = 1