python - Pandas 在 train_test_split 之后显示 SettingWithCopyWarning

标签 python pandas scikit-learn

<分区>

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

/usr/local/lib/python3.6/site-packages/pandas/core/indexing.py:179: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a 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

我使用以下版本:

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

Pandas :0.20.3

sklearn: 0.18.2

最佳答案

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

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

或者您可以使用 numpy.split(...) method

关于python - Pandas 在 train_test_split 之后显示 SettingWithCopyWarning,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45090639/

相关文章:

python - 在 python 中使用 scipy 的 kmeans2 函数

python - Pandas:在数据框中创建两个新列,其值是从预先存在的列中计算出来的

python - y_true 和 y_pred 具有不同数量的输出 (10!=1)

python - 多类分类 : probabilities and calibration

python - 特征数不匹配

python - 当给定 dict1 key2 时查找 dict1 key1 的值?

python - 如何将 numpy 数组创建为 xarray 数据数组?

python - epoll 如何在 Python 中检测客户端关闭?

python - pandas中 "flag"有什么用

python - 如何在 Windows cmd 上从 pip 安装 Pandas ?