熊猫在 train_test_split 后显示 SettingWithCopyWarning

Jon*_*han 3 python pandas scikit-learn

我正在尝试操作从 Sci-Kit Learn 的train_test_split操作中收到的数据帧。系统给了我以下信息:

/usr/local/lib/python3.6/site-packages/pandas/core/indexing.py:179: SettingWithCopyWarning: 试图在 DataFrame 的切片副本上设置值

以下内容在我的系统上引发警告:

import pandas as pd
from sklearn.model_selection import train_test_split
X=pd.DataFrame({'A':[2,5,7,8,9],'B':[2,5,3,51,5]})
(Xt,Xv)=train_test_split(X)
Xt.iloc[0,0]=6
Run Code Online (Sandbox Code Playgroud)

我使用以下版本:

python:'3.6.1(默认,2017 年 6 月 26 日,19:29:26)\n[GCC 4.9.2]'

熊猫:0.20.3

sklearn:0.18.2

Max*_*axU 7

您可以按如下方式解决它:

In [16]: Xt = Xt.copy()

In [17]: Xt.iloc[0,0]=6

In [18]: Xt
Out[18]:
   A  B
0  6  2
2  7  3
1  5  5

In [19]: X
Out[19]:
   A   B
0  2   2     # <--- NOTE: the value in the original DF has NOT been changed
1  5   5
2  7   3
3  8  51
4  9   5
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用numpy.split(...) 方法


All*_*len 5

另一种选择是重置 is_copy 平坦,但这似乎是 train_test_split 函数的错误。

Xt.is_copy=None
Run Code Online (Sandbox Code Playgroud)